Suppose there are 8 values in an array and the values are to be sorted using merge sort. The array list is to be divided into 4 sublist each of which contains 2 elements and the sublists are to be sorted. After sorting the sublists, two consecutive lists will be merged to form a new sublists. In our case 2 sublists will be formed and the sublists will be sorted again. The sorting technique can be selection sort, bubble sort or any other. Then again the sublists will be merged and sorting process will continue until it becomes a single list. Then finally the single list will be sorted. Suppose values are:
66 33 40 22 55 88 60 11 The groups will be like 66 33 40 22 55 88 60 11 After sorting we get 33 66 22 40 55 88 11 60 Now the new group 33 66 22 40 55 88 11 60 After sorting 22 33 40 66 11 55 60 88 The new group 22 33 40 66 11 55 60 88 After sorting 11 22 33 40 55 60 66 88
#include #include void sort(int arr[],int top,int size,int bottom) { float temp[20]; int f=top; int s=size+1; int t=top; int upper; while((f<=size)&&(s<=bottom)) { if(arr[f]<=arr[s]) { temp[t]=arr[f]; f++; } else { temp[t]=arr[s]; s++; } t++; } if(f<=size) { for(f=f;f<=size;f++) { temp[t]=arr[f]; t++; } } else { for(s=s;s<=bottom;s++) { temp[t]=arr[s]; t++; } } for(upper=top;upper<=bottom;upper++) { arr[upper]=temp[upper]; } } void pass(int arr[],int m,int n) { if(m!=n) { int mid=(m+n)/2; pass(arr,m,mid); pass(arr,mid+1,n); sort(arr,m,mid,n); } } void main() { int list[20]={22,1,23,3,43,4,3,2,55,4,5,6,7,11,12,23,45,67,8,9}; int i; printf("\nElements as follows\n"); for(i=0;i<20;i++) printf("%4d",list[i]); pass(list,0,19); printf("\nElements after sorting---as follows\n"); for(i=0;i<20;i++) printf("%4d",list[i]); }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|