Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sorting. 1. Sorting The most basic technique in programming So many solutions for it O( n 2 ), O( n lg n ), O( n ) depending on simplicity of mind complexity.

Similar presentations


Presentation on theme: "Sorting. 1. Sorting The most basic technique in programming So many solutions for it O( n 2 ), O( n lg n ), O( n ) depending on simplicity of mind complexity."— Presentation transcript:

1 Sorting

2 1. Sorting The most basic technique in programming So many solutions for it O( n 2 ), O( n lg n ), O( n ) depending on simplicity of mind complexity of insert operation

3 2. Sorting Algorithms Comparison Sort – O( n 2 ), O( n lg n ) Insertion sort Merge sort Heap sort Quick sort Counting Sort – O( n ) radix sort : extended counting sort Bucket Sort – O( n ) Why different complexities? use of smart data structure hide cost operations behind

4 3. Selection Sort

5 3. Selection Sort - slow 7884421256962634 78 4212 8442 26 42 347856 42 7842 56 968478

6 Pseudocode C Code 3. Selection Sort – the code

7 4. Insertion Sort

8 Insertion – Sort (A) for each j = 2 to length [ A ] do key = A [ j ] //Inserted into Sorted Subarray i = j – 1 while i > 0 & A [i] > key do A [i+1] = A [i] i = i – 1 A [i+1] = key 41 8 3627A 12345678I j key i 9 4 0 ji 7 9497 j 1 i 9 i 7 i 4 0 1 j 8 i 98 4. Insertion Sort – the code

9 Divide-and-Conquer Divide the array into two parts the value of x? pivot Conquer - do the same to each divided subarray Combine 5. Quick Sort

10 pivot: 6 5. Quick Sort Example

11

12 less than 6larger than 6

13 506324177531524288p = 5078 0123456789 jijjiijij 42 63 7531 ij 7531753150241752887842 63 7531 528878637524174231p = 31 012356789 ij 4217 iij 4224 422431174224 174224p = 24 ji 1724 17p = 17 17 p = 75 ijiijj 7563 Step skipped 528878 63 528878 63 52 63 52 7888 78 j = 4 j = 2 j = 0 sentinel j

14 5. Quick Sort Algorithm

15 Details

16 quicksort(int s[], int l, int h) { int p; /* 분할을 위한 인덱스 */ if ((h-l)>0)) { p = partition(s, l, h); quicksort(s, l, p-1); quicksort(s, p+1, h); } int partition(int s[], int l, int h) { int i; /* counter */ int p; /* 피벗 원소의 인덱스 */ int firsthigh; /* 피벗을 위한 디바이더 위치 */ p = l; firsthigh = l; for (i=l; i<h; i++) if (s[i] < s[p]) { swap(&s[i], &s[firsthigh]); firsthigh++; } swap(&s[p], &s[firsthigh]); return(firsthigh); } the code What if p=h?

17 Library #include void qsort(void *base, size_t nel, size_t width, int (*compare) (const void *, const void *)); array: base number of elements: nel size of each element: width bytes you should provide compare function like int mycompare(int *i, int *j) { if (*i > *j) return (1); elseif (*i < *j) return (-1); else return (0); } qsort destroys the original array

18 Library Usage


Download ppt "Sorting. 1. Sorting The most basic technique in programming So many solutions for it O( n 2 ), O( n lg n ), O( n ) depending on simplicity of mind complexity."

Similar presentations


Ads by Google