Yesterday I went for an interview,
He asked me to write a program to sort an array in ascending order.
I wrote a program which is as follows,
var mySortOne = function(myArray){
var num = 0,
temp = 0,
isSwipe = false,
counter = 0;
for(num = 0; num < myArray.length; num++){
print((++counter)+" => "+myArray);
if (((num+1) < myArray.length) && (myArray[num] > myArray[num+1])){
temp = myArray[num+1];
myArray[num + 1] = myArray[num];
myArray[num] = temp;
isSwipe = true;
}
if(isSwipe){
isSwipe = false;
num = -1;
}
}
print("\n FINAL "+myArray);
};
mySortOne([45,12,78,22,4]);
The interviewer was not satisfied, he said "I am not asking for optimum solution, but your sorting algorithm is worst that n^2."
So I wrote a second solution, which is as follows,
var mySortTwo = function(myArray){
var num = 0,
MAX = myArray.length,
isSwipe = false,
temp = 0,
counter = 0;
do{
isSwipe = false;
for(num = 0; num < MAX; num++){
print((++counter)+" => "+myArray);
if(((num + 1) < MAX) && (myArray[num] > myArray[num+1])){
temp = myArray[num + 1];
myArray[num + 1] = myArray[num];
myArray[num] = temp;
isSwipe = true;
}
}
MAX--;
}while(isSwipe);
print("\n FINAL "+myArray);
};
mySortTwo([45,12,78,22,4]);
But still he was not satisfied.
I had some print statements of both the algorithm.
The first algorithm's output is
1 => 45,12,78,22,4
2 => 12,45,78,22,4
3 => 12,45,78,22,4
4 => 12,45,78,22,4
5 => 12,45,22,78,4
6 => 12,45,22,78,4
7 => 12,22,45,78,4
8 => 12,22,45,78,4
9 => 12,22,45,78,4
10 => 12,22,45,78,4
11 => 12,22,45,4,78
12 => 12,22,45,4,78
13 => 12,22,45,4,78
14 => 12,22,4,45,78
15 => 12,22,4,45,78
16 => 12,4,22,45,78
17 => 4,12,22,45,78
18 => 4,12,22,45,78
19 => 4,12,22,45,78
20 => 4,12,22,45,78
21 => 4,12,22,45,78
FINAL 4,12,22,45,78
And the output of second algorithm is as follows,
1 => 45,12,78,22,4
2 => 12,45,78,22,4
3 => 12,45,78,22,4
4 => 12,45,22,78,4
5 => 12,45,22,4,78
6 => 12,45,22,4,78
7 => 12,45,22,4,78
8 => 12,22,45,4,78
9 => 12,22,4,45,78
10 => 12,22,4,45,78
11 => 12,22,4,45,78
12 => 12,4,22,45,78
13 => 12,4,22,45,78
14 => 4,12,22,45,78
15 => 4,12,22,45,78
FINAL 4,12,22,45,78
He said both are iterating too much. We can have a better solution using simple bubble sort.
But what I think is my second solution is a bubble sort itself.
Can you please tell me what are the complexity for both the algorithms, and how come I can improve the second bubble sort
FINAL 12,4,22,45,78O(n²), or did he mean that (some) complexity is worse thanO(n²)?