I have question in my assignment says:
Given an unsorted array whose elements are all 0 (zeros) or 1 (ones),
write code to sort the array so that all the 0’s appear first, followed by all the 1’s.
You may assume that ‘num_elements’ always accurately indicates the number of elements
in the array.
Please use the following function header:
void sort_elements(int array[], int num_elements);
I realy have no idea what he means by that, did he want two arrays or just one. Please explain to me.
I did it 😀 I can’t believe myself ,, i used 2 for loops with 2 if in it
.. thank u all for ur assistance guys <3 <3
public class Q4 {
public static void main (String []args){
int Sky[]={0,0,1,1,0,1};
sort_elements(Sky,Sky.length);
}
public static void sort_elements(int array[],int num_elements){
for ( int i=0; i < num_elements ; i++){
if ( array[i]==0){
System.out.println(array[i]);
}
}
for ( int i=0; i<num_elements ; i++){
if ( array[i]==1){
System.out.println(array[i]);
}
}
}
}
1) Maintain two pointers left and right.
2) Start traversing left pointer towards right until 1 is encountered.
3) Start right pointer towards left until 0 is encountered.
4) set array[left] = 0, array[right] = 1
5) Continue doing so until left and right pointer converge.
6) Since, we have to traverse the array only once, sorting happened in O(n) time.