Wednesday, March 21, 2007

Incredible Merge Sort :)

Today, i have written lots of sorting algorithms like bubble sort, selection sort, insertion sort, shell sort etc.
However, i have never implemented a merge sort which uses no temporary list to store the sorted sequences. And i have decided a merge sort algorithm like that.
It has some computational complexity but the main idea is simple. Every time in the merge operation we merge two lists which are indeed part of a one list! So i can use them as one list. It means if I overflow in the first list then i reach the second list! Also you should note that, it has some extra costs because i have to shift array elements for placing them to correct locations. This cost doesnt exist if you use extra lists to store the sorted sequences.
The merge code isnt so clear, may be you dont understand some parts because i dont give importance to naming conventions. Maybe i can revise and post it later. But now, i want to show you the code. If you find some bug please contact with me :)

template<typename T>
void mergeSort( T* arr , int len ){

int left, right, middle;

if( !arr || len < 2)
return;

left = 0;
right = len;
middle = left + ((right-left)/2 );

mergeSort( arr , middle - left );
mergeSort( arr+middle , right - middle);
merge(arr , middle-left , right-middle);
}


template<typename T>
void merge( T* left , int len1 , int len2 ){

int i,j ,k, ind , total = len1 + len2;
T val;


for(i = 0, j = 0; i < j+len1 && j < len2 ;){
if( left[i] > left[j+len1]){
val = left[ j + len1 ];
ind = j + len1 - i ;
k = 0;
while( ind >= 0 ){
left[j + len1 + k] = left[j + len1 +k -1];
k--;
ind--;
}
left[i] = val;
j++;
}else
i++;
}
}


For calling mergesort algorithm, just create an array of integers, chars or anything which overloads the > operator and call the method by giving the array and its size.

mergeSort( arr , size );

See you soon...

No comments: