Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm.

Presentation on theme: "Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm."— Presentation transcript:

Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm

Sorting- problem definition A sorting algorithm is an algorithm that puts elements of a list in a certain order. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. 2

Sorting- algorithms properties 3

Comparison sorting 4

Quicksort quickSort(A) quickSort(A, 0, A.length) quickSort(A, low, high) if (high > low){ pivot  partition(A, low, high) quickSort(A, low, pivot-1) quickSort(A, pivot+1, high) } 5

Quicksort cont’d partition routine chooses a pivot, partitions the array around it and returns its index. 6 4172112391156 17211239146 low pivot high leftright left Swap! left right 1517211293146 right left 1517211296143 pivot

Quicksort cont’d int partition( A, low, high ) pivot_item  A[low] left  low, right  high, pivot  left while ( left < right ) { while (left < high && A[left] ≤ pivot_item) // Scan right left++ while (A[right] > pivot_item) // Scan left right-- if (left < right) swap(A, left, right) } // Right is the final position of the pivot swap(A, pivot, right) return right 7

Quicksort cont’d 8

Question 1 9

Question 1 cont’d The solution is based on quicksort algorithm. Select(k, S) { // Returns k-th element in S. pick x in S partition S into L, E, G such that: max(L) < x, E = {x}, x < min(G) if k ≤ length(L) // Searching for item ≤ x return Select(k, L) else if k ≤ length(L) + length(E) // Found return x else // Searching for item ≥ x return Select(k - length(L) - length(E), G) 10

Question 1 cont’d 11

Question 2 12

Question 2 cont’d 13

Question 2 cont’d 14

Question 3 15

Question 3 cont’d 16

Question 4 Given the following algorithm to sort an array A of size n, argue its correctness and find its recurrence formula. newSort(A) if |A| = 2 if A[0] > A[1] swap(A, 0, 1) retutn A else newSort(A[1..2n/3]) // Sort recursively the first 2/3 of A newSort(A[n/3+1..n]) // Sort recursively the last 2/3 of A newSort(A[1..2n/3])) // Sort recursively the first 2/3 of A 17

Question 4 cont’d 18

Question 4 19

Question 4 cont’d 20

Download ppt "Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm."

Similar presentations