Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 162 Intro to Programming II Quick Sort 1. Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage.

Similar presentations


Presentation on theme: "CS 162 Intro to Programming II Quick Sort 1. Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage."— Presentation transcript:

1 CS 162 Intro to Programming II Quick Sort 1

2 Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage over MergeSort: no temporary arrays to sort and merge the partial results 2

3 Quicksort Has two steps: 1.Partition the data around a special element called the pivot 2. Recursively sort each partition 3

4 Quicksort Pick the first element (ie. 5) as the pivot. Everything = 5 goes in the right partition Before partioning After partioning 4 5 3 2 6 4 137 5 3 2 1 4 637 Left Right

5 Quicksort After partioning To continue you apply the algorithm to each partition: 1.Find the pivot 2.Partion that partition 5 5 3 2 1 4 637 Left Right

6 Quicksort int partition(int a[], int from, int to) { int pivot = a[from]; int i = from – 1; int j = to + 1; while (i < j) { i++; while (a[i] < pivot) i++; j--; while (a[j] > pivot) j--; if( i < j ) swap(i, j); } return j; } 6

7 Quicksort /** * Code snippet for Quicksort * from and to specify the range of the array that * you want to sort. For example, from = 0 and to = array size - 1 will sort the entire array. */ void quicksort(int a[], int from, int to) { if (from >= to) return; int p = partition(a, from, to); quicksort(a, from, p); quicksort(a, p+1, to); } 7

8 Complexity 8 Best Case- scrambled O(n log n) Worst Case- already sortedO(n 2 ) Average Case- randomly picked pivot O(n 2 )


Download ppt "CS 162 Intro to Programming II Quick Sort 1. Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage."

Similar presentations


Ads by Google