快速排序 分区函数

适合我的快排分区函数:

1
2
3
4
5
6
7
8
9
def patition2(arr, l, r):
    pivot = arr[l]
    index = l+1
    for i in range(l+1, r+1):
        if arr[i] < pivot:
            arr[i], arr[index] = arr[index], arr[i]
            index += 1
    arr[l], arr[index-1] = arr[index-1], arr[l]
    return index-1  

 

注意要点:

1、返回index-1,非常关键!!!因为 assert arr[index-1] < pivot and arr[index]>=pivot

2、注意判定条件是 <,当然 <= 也是可以的!!!

3、注意index起始位置是L+1

4、循环的起始位置也是L+1

 

网上的其他写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// C++
void Swap(int &first_number, int &second_number) {
    int temp        = first_number;
    first_number    = second_number;
    second_number   = temp;
}
 
int Partition(int array[], int start, int end, int pivot_index) {
    int pivot       = array[pivot_index];
    int store_index = start;
 
    Swap(array[pivot_index], array[end]);
    for (int iLoop = start; iLoop < end; iLoop++) {
        if (array[iLoop] < pivot) {
            Swap(array[iLoop], array[store_index]);
            store_index++;
        }
    }
    Swap(array[store_index], array[end]);
 
    return store_index;
}

  

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<class T>
int Partition(T a[], int start, int end, int pivotIndex){
    T pivot = a[pivotIndex];
    Swap(a[pivotIndex], a[end]);
    int storeIndex = start;
    for(int i = start; i < end; ++i) {
        if(a[i] < pivot) {
            Swap(a[i], a[storeIndex]);
            ++storeIndex;
        }
    }
    swap(a[storeIndex], a[end]);
    return storeIndex;
}

  

 

分区的思想,还可以用在解决计算中值和选择问题上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    //中值问题
public static int getMedian(int[] array){
    return getKth(array,array.length/2);
}
//选择问题
public static int getKth(int[] array,int k){
    int low =0,high = array.length -1;
    int s = 0;
    do{
        s = partition(array,low,high);
        if(s>k) high = s-1;
        else low = s+1;
    }while(s != k);
    return array[s];
}

  

posted @   bonelee  阅读(760)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-01-02 137. Single Number II——问题是查找,本质是hash查找,只是记录的是32 bit中各个位出现次数而已
2017-01-02 46. Permutations——本质和树DFS遍历无异 fun: for i in nums fun(i)
2017-01-02 328. Odd Even Linked List——多利用fake_head
2017-01-02 449. Serialize and Deserialize BST——几乎所有树的面试题目都会回到BFS或者DFS,使用BFS,None节点存#
点击右上角即可分享
微信分享提示