快速排序算法里的partition函数

来源:互联网 发布:java 生成pdf表格 编辑:程序博客网 时间:2024/05/20 19:28

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


代码实现:

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

原创粉丝点击