I was trying to solve a problem:
Problem:
Given an array of Positive repetitive numbers. Output should give an array with odds sorted on the right and evens on the left (no particular order)
Input : [4,1,2,3,4]
Output: [4,2,3,1]
Solve it In-place and without using extra space and O(N) runtime.
Code:
/*
* Algorithm is simple, have two pointers one on the left and another on the right.
* Note: We are sorting all evens on the left and odds on the right
* If you see even on left, move on else swap.
*/
function groupNumbers(intArr) {
if(intArr.length == 0 || intArr.length == 1){
return intArr;
}
for(let i=0, j =intArr.length-1; i<intArr.length; i++){
if(j>=i){ //elements should not overlap
let start = intArr[i];
let end = intArr[j];
if(start%2 == 0){ //Even
i++;
} else {
[start, end] = [end, start]; //swap
}
if(end%2 == 1){
j--;
} else {
[start, end] = [end, start]; //swap
}
} //if-ends
}//for-ends
return intArr;
}
I'm not sure where I'm going wrong. I'm missing something. I'm getting the same sorted array as output.
Condition: **SOLVE it INPLACE and without using extra space ** (Preferably in ONE iteration)
Array.prototype.sortis implemented in C++ and will almost certainly be faster, even with a custom sorting function passed in, than anything you will write.