ckook

导航

 

快速排序算法里的partition函数用来解决这样一个问题:给定一个数组arr[]和数组中任意一个元素a,重排数组使得a左边都小于它,右边都不小于它。

 // arr[]为数组,start、end分别为数组第一个元素和最后一个元素的索引
// povitIndex为数组中任意选中的数的索引
1
int partition(int arr[], int start, int end, int pivotIndex) 2 { 3 int pivot = arr[pivotIndex]; 4 swap(arr[pivotIndex], arr[end]); 5 int storeIndex = start;
6 //这个循环比一般的写法简洁高效,呵呵维基百科上看到的 7 for(int i = start; i < end; ++i) { 8 if(arr[i] < pivot) { 9 swap(arr[i], arr[storeIndex]); 10 ++storeIndex; 11 } 12 } 13 swap(arr[storeIndex], arr[end]); 14 return storeIndex; 15 }

 

posted on 2012-10-24 22:35  ckook  阅读(17214)  评论(2)    收藏  举报