Apr 12, 2012

Sorting integer array in place, in linear time

Recently when I was learning algorithms, I came up with a pretty handy sorting method that can sort integer array in place, in linear time under the assumption that all the elements in input array are distinct and their values are 1~n(or 0~n-1) where n is the length of input array. So I decided to write a reminder to myself.
Here's the algorithm:

1:  gonnaSortIndex=len(array)-1  
2:  for i=len(array)-1;i>0 {//Note that there's no i-- here
3:    correctIndex=array[gonnaSortIndex]  
4:    if correctIndex!=gonnaSortIndex {  
5:      array[correctIndex],array[gonnaSortIndex]=array[gonnaSortIndex],array[correctIndex] //swapping array[gonnaSortIndex] into its final position and place the swapped out element array[correctIndex] into array[gonnaSortIndex].  
6:   } else {  
7:     i--  
8:     gonnaSortIndex=i  
9:   }  
10: }

This algorithm is clearly in-place, now let's examine what's the possible worst running time~

Although not 100% sure because I did't really prove it but I think in the worst case, the running time is 2(n-1) where n is the # of elements in array
Here's the worst case(that I came up with so far):
Assume we swap all elements into their correct positions while i remains len(array)-1 all the time, so that it will take n-1 times executing if clause on line 4. After that we spend n-1 times executing else clause on line 6 so total running time is: 2*(n-1).
If there's any mistakes, can someone please point it out cause I'm eager to know whether this actually works in all situation under the assumption above.

No comments:

Post a Comment

Just leave a message :)