Presentation is loading. Please wait.

Presentation is loading. Please wait.

SORTING Sorting is the process of rearranging a set of objects in a specific order. Internal sorting (sorting of arrays) External sorting (sorting of sequential.

Similar presentations


Presentation on theme: "SORTING Sorting is the process of rearranging a set of objects in a specific order. Internal sorting (sorting of arrays) External sorting (sorting of sequential."— Presentation transcript:

1 SORTING Sorting is the process of rearranging a set of objects in a specific order. Internal sorting (sorting of arrays) External sorting (sorting of sequential files) Simple Sorting methods: insertion Sort selection Sort exchange Sort

2 Insertion sort The items are divided into a sorted sequence a[0]... a[i-1] and a source sequence a[i]... a[n-1]. FOR i := 1 TO n-1 DO x := a[i]; insert x at the appropriate place in a[0]... a[i] END

3 Insertion sort А = 18, 20, 5, 13, 15

4 Insertion sort for (i=1; i<n; i++) { j=i; temp=a[i]; while(j>0 && temp<a[j-1]) { a[j]=a[j-1]; j--; } a[j]=temp; } //i determines sequence a[0]...a[i] //moving // insert

5 Insertion sort O(n 2 )

6 Binary insertion sort void binsort(int a[], int n) {int item; for (int i=1; i<n; i++) { item=a[i]; int l=0; int r=i-1; while (l<=r) { int m=(l+r)/2; if (item<a[m]) r=m-1; else l=m+1; } for (int j=i-1; j>=l; j--) a[j+1]=a[j]; a[l]=item; }} O(n 2 )

7 Insertion Sort by Diminishing Increment 1, 4, 13, 40, 121,... h k-1 = 3h k +1, h t-1 = 1, t = log 3 (n) - 1. 1, 3, 7, 15, 31,... h k-1 = 2h k +1, h t-1 = 1, t = log 2 (n) - 1.

8 Insertion Sort by Diminishing Increment void shellsort(int *a, int n) {int h[4]={1,3,5,9}; int k=3; for (int j=k; j>=0; j--) for (int i=1; i-h[j]>=0&&i<n; i++) { int l=i; int temp=a[i]; while (l>0 && temp<a[l-h[j]]) { a[l]=a[l-h[j]]; l=l-h[j]; } a[l]=temp; } O(n 2 )

9 Selection sort 1. Select the item with the smallest key. 2. Exchange it with the first item a[0]. 3. Then repeat these operations with the remaining n-1 items, then with n-2 items, until only one item - the largest - is left. FOR i := 0 TO n-1 DO assign the index of the least item of a[i]... a[n-1] to k; exchange a[i] with a[k] END

10 Selection sort Example: Array: 18, 20, 5, 13, 15. O(n 2 )

11 Selection Sort void selectsort(int A[],int n) { int k; int i, j; for (i=0;i<n-1;i++) { k=i; for (j=i+1;j<n;j++) if(A[j]<A[k]) k=j; int temp=A[i]; A[i]=A[k]; A[k]=temp; }}


Download ppt "SORTING Sorting is the process of rearranging a set of objects in a specific order. Internal sorting (sorting of arrays) External sorting (sorting of sequential."

Similar presentations


Ads by Google