Quick Sort - PowerPoint PPT Presentation

About This Presentation
Title:

Quick Sort

Description:

Quick Sort By: HMA RECAP: Divide and Conquer Algorithms Divide and Conquer Algorithms Quicksort An element of the array is chosen. We call it the pivot element. – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 10
Provided by: lehighEdu
Category:
Tags: quick | sort | swap

less

Transcript and Presenter's Notes

Title: Quick Sort


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
A1N
Add(A array, min, max)
  1. If min max then return Amin
  2. If min gt max then return 0
  3. mid ? floor((minmax)/ 2)
  4. FirstHalf ? Add(A,min, mid - 1)
  5. SecondHalf ? Add(A, mid 1,max)
  6. Return FirstHalf SecondHalf Amid

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 (AL..R)
  • if L lt R then
  • pivot Partition( AL..R)
  • Quicksort (A1..pivot-1)
  • Quicksort (Apivot1...R)

7
Partition Algorithm
  • Partition (AL..R)
  • p ? AL i ? L j ? R 1
  • while (i lt j) do
  • repeat i ? i 1 until Ai p
  • repeat j ? j ? 1 until Aj p
  • if (i lt j) then swap(Ai, Aj)
  • swap(Aj,AL)
  • 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

every partition splits half of the array
T(n) n 2T(n/2) T(1) 1 O(n log2n)
one array is empty one has all elements
T(n) n T(n-1) T(1) 1
O(n2 )
O(n log2n)
Write a Comment
User Comments (0)
About PowerShow.com