cs 162 intro to programming ii quick sort 1. quicksort maybe the most commonly used algorithm...

8
CS 162 Intro to Programming II Quick Sort 1

Upload: susanna-hicks

Post on 18-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

1

CS 162Intro to Programming II

Quick Sort

Page 2: 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

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

Page 3: 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

3

Quicksort

Has two steps:

1. Partition the data around a special element called the pivot

2. Recursively sort each partition

Page 4: 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

4

Quicksort

Pick the first element (ie. 5) as the pivot. Everything < 5 goes in the left partition, everything >= 5 goes in the right partition

Before partioning

After partioning

5 3 2 6 4 1 3 7

5 3 2 1 4 63 7

Left Right

Page 5: 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

5

Quicksort

• After partioning

To continue you apply the algorithm to each partition: 1. Find the pivot2. Partion that partition

5 3 2 1 4 63 7

Left Right

Page 6: 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

6

Quicksortint 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;

}

Page 7: 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

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);

}

Page 8: 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

8

Complexity

Best Case- scrambled O(n log n)

Worst Case- already sorted O(n2)

Average Case- randomly picked pivot O(n2)