Presentation is loading. Please wait.

Presentation is loading. Please wait.

Quick Sort By: HMA. RECAP: Divide and Conquer Algorithms This term refers to recursive problem-solving strategies in which 2 cases are identified: A case.

Similar presentations


Presentation on theme: "Quick Sort By: HMA. RECAP: Divide and Conquer Algorithms This term refers to recursive problem-solving strategies in which 2 cases are identified: A case."— Presentation transcript:

1 Quick Sort By: HMA

2 RECAP: Divide and Conquer Algorithms This term refers to recursive problem-solving strategies in which 2 cases are identified: A case for a direct (non recursive) solution A case for a recursive solution containing the following elements:  Dividing the input into smaller problems  Finding recursive solutions for smaller problems  Combining the solutions for the smaller problems

3 Divide and Conquer Algorithms Suppose we want to add the elements in an array A[1…N] Add(A : array, min, max) 1.If min = max then return A[min] 2.If min > max then return 0 3.mid  floor((min+max)/ 2) 4.FirstHalf  Add(A,min, mid - 1) 5.SecondHalf  Add(A, mid + 1,max) 6.Return FirstHalf + SecondHalf + A[mid] Direct solution Dividing input Solve smaller Combining solutions Complexity = O(Dir) + O(Div) + O(Smaller) + O(Combining)

4 Quicksort An element of the array is chosen. We call it the pivot element. The array is rearranged such that - all the elements smaller than the pivot are moved before it - all the elements larger than the pivot are moved after it Then Quicksort is called recursively for these two parts.

5 Example A [3 8 5 2 7 1 6 4]

6 Quicksort - Algorithm Quicksort (A[L..R]) if L < R then pivot = Partition( A[L..R]) Quicksort (A[1..pivot-1]) Quicksort (A[pivot+1...R)

7 Partition Algorithm Partition (A[L..R]) p  A[L]; i  L; j  R + 1 while (i < j) do { repeat i  i + 1 until A[i] ≥ p repeat j  j  1 until A[j] ≤ p if (i < j) then swap(A[i], A[j]) } swap(A[j],A[L]) return j Questions: Why not choose for p the middle position in the array? Complexity?

8 Example (again) A [3 8 5 2 7 1 6 4]

9 Complexity Analysis Best Case: Worst Case: Average case: T(n) = n + T(n-1) T(1) = 1 O(n 2 ) O(n log 2 n) T(n) = n + 2T(n/2) T(1) = 1 O(n log 2 n) every partition splits half of the array one array is empty; one has all elements


Download ppt "Quick Sort By: HMA. RECAP: Divide and Conquer Algorithms This term refers to recursive problem-solving strategies in which 2 cases are identified: A case."

Similar presentations


Ads by Google