Array Even Odd Sorting LeetCode (Segregate Even and Odd Numbers)

Given an array of integers, write a method to organize it in a way that all even numbers come in the beginning and all the odd numbers come in the end. Can you try without additional storage?
 
This problem is popular in LeetCode and GeeksForGeeks A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions
 
Approach:
  1. create two pointers p1 and p2. p1 points to begining of the array and p2 to the end
  2. repeat while p1<p2 
    1. if index p1 has even element, increase p1 
    2. if index p2 has odd element, decrease p2 
    3. if index p1 has odd element
      1. we need to send it to right by swapping with the even item on right 
    4. if index p2 has even element, we need to bring it to left by swapping with the odd in the left

Solution:


No comments:

Post a Comment