coursera review---algorithms,Stanford---02---quick sort
the idea of quick sort is:
- choose a pivot(randomly or simply)
- partition the array into a[0,1,...,pivot-1],a[pivot],a[pivot+1,...,end] that all elements in a[0,1,...,pivot-1] < a[pivot],and all elements in a[pivot+1,...,end] >= a[pivot]
- quick sort a[0,1,...,pivot-1]
- quick sort a[pivot+1,...,end]
1 void swap(int a[], int i, int j) { 2 int temp = a[i]; 3 a[i] = a[j]; 4 a[j] = temp; 5 } 6 7 // always take a[left] as the pivot 8 int partition(int a[], int left, int right) { 9 int j = left + 1; // index j for seeking first element >= pivot 10 for (int i = j; i <= right; i++) { 11 if (a[i] < a[left]) { 12 swap(a, i, j); 13 ++j; 14 } 15 } 16 swap(a, left, j - 1); 17 return j - 1; 18 } 19 20 void quickSort(int a[], int left, int right) { 21 if (left < right) { 22 int p = partition(a, left, right); 23 quickSort(a, left, p - 1); 24 quickSort(a, p + 1, right); 25 } 26 }
the worst running time of quick sort can be O(n^2)
but if randomly choose pivot,the running time of quick sort can be expected to be O(nlg(n))
use the partition subroutine,we can solve the select problem:find the ith smallest element in an array
posted on 2013-08-17 16:20 haoyancoder 阅读(246) 评论(0) 收藏 举报