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

of 18/18
Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm
  • date post

    14-Dec-2015
  • Category

    Documents

  • view

    223
  • download

    4

Embed Size (px)

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

  • Slide 1

Foundations of Data Structures Practical Session #11 Sort properties, Quicksort algorithm Slide 2 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 Slide 3 Sorting- algorithms properties 3 Slide 4 Comparison sorting 4 Slide 5 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 Slide 6 Quicksort contd 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 Slide 7 Quicksort contd 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 Slide 8 Quicksort contd 8 Slide 9 Question 1 9 Slide 10 Question 1 contd 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 Slide 11 Question 1 contd 11 Slide 12 Question 2 12 Slide 13 Question 2 contd 13 Slide 14 Question 2 contd 14 Slide 15 Question 3 15 Slide 16 Question 3 contd 16 Slide 17 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 Slide 18 Question 4 contd 18 Slide 19 Question 4 19 Slide 20 Question 4 contd 20