{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

15 - Quicksort

# 15 - Quicksort - Quicksort Suppose we want to sort the...

This preview shows pages 1–2. Sign up to view the full content.

CPSC 260 Quicksort Page 1 Quicksort Suppose we want to sort the elements in an array between the left and right indices: 2 -3 5 1 6 -4 3 7 Step 1: find a pivot element and swap this element with the element at position left . There are many different ways in which this can be done. We will start with a very naïve method: choose the pivot to be the element that is already in position left so that no swapping is necessary. 2 -3 5 1 6 -4 3 7 CPSC 260 Quicksort Page 2 We now try to partition the array so that elements on the left side are less than or equal to the pivot element and elements on the right side are greater than the pivot element. Step 2: increment left until we find an element that is greater than or equal to the pivot element or until left > right 2 -3 5 1 6 -4 3 7 Step 3: until we find an element that is less than or equal to the pivot element, decrement right 2 -3 5 1 6 -4 3 7 Step 4: if left < right , swap elements at positions left and right . 2 -3 1 6 3 7 -4 5 CPSC 260 Quicksort Page 3 Step 5: Repeat the above process until left >= right Step 6: Swap pivot element with element at position right 2 -3 -4 1 6 5 3 7 2 -3 -4 1 6 5 3 7 2 -3 -4 1 6 5 3 7 -3 -4 6 5 3 7 2 1 CPSC 260 Quicksort Page 4 Step 7: The pivot element is now in the correct position in the array. We now recursively apply Quicksort to the left and right partitions until the entire array is sorted 1 -3 -4 2 6 5 3 7 left partition right partition We have then sorted everything because the small elements are (sorted) in the left partition, the pivot is in the middle, and all the large elements are (sorted) in the right partition. CPSC 260 Quicksort Page 5 Coding the Quicksort Algorithm We will not examine a complete implementation of the Quicksort algorithm here but simply focus on the top-level implementation and then examine the time and space complexity of the algorithm… We will use the “Big Oh ” notation for this. f(n) is O(1) if it is no larger than some c f(n) is O(n) if it is no larger than c·n for some c f(n) is O(g(n)) if it is no larger than c·g(n) for some c So when can we say that f(n) is O(n log n)?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 4

15 - Quicksort - Quicksort Suppose we want to sort the...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online