Write a program to group given set of numbers by placing all the even numbers first and then all odd numbers with O(n) time complexity and O(1) space complexity.
https://github.com/prasune/Algorithms/tree/master/src/main/java/com/test/algorithm
package com.test.algorithm;
public class GroupByEvenAndOdd {
public static void main(String[] args) {
int[] numArray = new int[]{4,2,5,8,12,11,10};
groupNumsByEvenAndOdd(numArray);
for (int i=0; i< numArray.length; i++) {
System.out.println(numArray[i]);
}
}
private static void groupNumsByEvenAndOdd(int[] numArray) {
int newEvenIndex = 0;
for (int i=0; i< numArray.length; i++) {
if(numArray[i]%2 == 0) {
if (i != newEvenIndex) {
// swap
int temp = numArray[newEvenIndex];
numArray[newEvenIndex] = numArray[i];
numArray[i] = temp;
}
newEvenIndex++;
}
}
}
}
No comments:
Post a Comment