【快排】quickSort, introsort(C++ Sorting Weapon), 3-way quickSort

文章结构如下:
一、quickSort (recursive)
二、introsort
三、3-way quickSort
四、quickSort (iterative)

一、quickSort (recursive)

  快排 quicksort,也被称为 partition-exchange sort,是面试最基础的问题,思想很简单,就是分治法,选一个 pivot,比它小的放左边,比它大的放右边,然后分别对左右两边进行排序。
  https://www.geeksforgeeks.org/quick-sort/ , 这里边讲的挺好的。

Like Merge Sort, QuickSort is a Divide and Conquer algorithm. 
It picks an element as pivot and partitions the given array around the picked pivot. 
There are many different versions of quickSort that pick pivot in different ways:

  pivot 的选法有很多种,第一个,最后一个,随机,中位数等,“quicksort” 这部分就用比较简单的选最后一个数,后边 introsort 用的是中位数。
  Pseudo Code(伪代码)在上边网址中有,还有详细的注释。用 C++ 写类似下边这样:

int partition(vector<int>& arr, int low, int high) {
	int pivot = arr[high], idx = low;
	for (int i = low; i < high; ++i)
		if (arr[i] <= pivot)
			swap(arr[idx++], arr[i]);
	swap(arr[idx], arr[high]);
	return idx;
}

void quickSort(vector<int>& arr, int low, int high) {
	if (low < high) {
		const int pivot = partition(arr, low, high);
		quickSort(arr, low, pivot - 1);
		quickSort(arr, pivot + 1, high);
	}
}

  Note:
  1、 quicksort 默认情况是不稳定的排序,因为出现和pivot值相同的数时,可能这些数可能被放到pivort左边也可能被放到pivot右边,所以原来的顺序就变了,但是,any sorting algorithm can be made stable by considering indexes as comparison parameter.也就是任何排序都是可以通过对索引的比较判断让他变成稳定的(只不过没什么必要而已)
  2、 quicksort 平均时间复杂度是 O(NlogN),最坏情况时间复杂度是 O(N2),最坏情况什么时候发生肯定要知道:就是每次选取 pivot 之后,划分左右两边都是只有一边,另一边每次都没有数(也就是每次选的 pivot 都是目前未排序的最大的或最小的),比如说 “1 2 3 4 5”,这个已排序数组,或者 “5 4 3 2 1”,每次 pivot 选最后一个数的话,每次都不会将原始数组分成大小差不多的两端,而是分成比原来少一个数的一个大段,时间复杂度就是 O(N2)了。
  3、 虽然 quicksort 的最坏时间复杂度比 heapsort(堆排序)mergesort(归并排序) 这样最坏时间复杂度都是 O(NlogN) 的看起来要慢,但是 inpractice,还是 quicksort 更快,因为快排的内部循环在很多结构和真实数据上更高效,并且快排可以通过 pivot 的选择让最坏情况不发生。However, merge sort is generally considered better when data is huge and stored in external storage. 归并排序被认为在很大的存储在外部空间中的数据上会更好。
  4、 quicksort 是尾递归"Quick Sort is also tail recursive, therefore tail call optimizations is done."

二、introsort

  introsort 全称是 introspective sort,直译就是 “好反省的排序”。 是 C++ STL 使用的 sort 算法
  https://www.geeksforgeeks.org/know-sorting-algorithm-set-1-sorting-weapons-used-programming-languages/ 里写了常用语言的内置 sort 方法。
  introsort 是一种混合(hybrid)排序算法,因为它用了不止一种排序,用到了 Quicksort, Heapsort and Insertion Sort 三种。简单的理解就是:

  1. 当 introsort 可能会超过最大深度限制的时候,使用 堆排序(We define the maximum depth limit as 2*log(N))
  2. 当数据规模非常小的时候(小于 16 的时候),使用 插入排序(We define this cutoff as 16
  3. 当数据规模不大不小的时候,使用 快排

  Note: introsort 使用的快排,pivot 的选取是 “三点中值法”,就是每次选取的 pivot,是第一个数、最后一个数、中间,三个位置的值中的中位数,这样可以有效避免最坏情况发生(《C++ STL 源码剖析》中有写)。

三、3-way quickSort

  三路快排出现的目的,是处理像 {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4} 这样 redundant 的数组,正常的快排,如果选 pivot 为 4,那每次就只对一个 4 进行了排序,3-way quickSort 的思想就是将划分为两端改为划分为三段:1、小于,2、等于,3、大于。3-way quicksort 可以用返回 pair 的形式实现,如下:

pair<int, int> partition(vector<int>& arr, int l, int r) {
	// start 是第一轮交换完,第一个 > pivot 的位置, end 是第一个 == pivot 的位置
	int start = l, end = r;
	const int pivot = arr[r];	// 用最后一个元素作为 pivot
	// 先把 < pivot 的换到前边,== pivot 的换到最后边
	for (int i = l; i < end; )
		if (arr[i] < pivot) swap(arr[i++], arr[start++]);
		else if (arr[i] == pivot) swap(arr[i], arr[--end]);
		else ++i;
	// 最后把 == pivot 的换到中间
	// end-start 是 > pivot 的有多少个, r-end+1 是 == pivot 有多少个,选少的换
	const int m = min(end - start, r - end + 1);
	for (int i = 0; i < m; ++i)
		swap(arr[start + i], arr[r - i]);

	return make_pair(start, start + r - end);	// start + (r - end + 1) - 1
}

void threeWayQuickSort(vector<int>& arr, int l, int r) {
	if(l < r) {
		const auto pivots = partition(arr, l, r);
		threeWayQuickSort(arr, l, pivots.first - 1);
		threeWayQuickSort(arr, pivots.second + 1, r);
	}
}

四、quickSort (iterative)

  快排的思想其实是很适合写成递归形式的,而且递归形式的代码不需要复制空间存储数据,只需要栈空间存储函数调用。不过快排还是可以写成迭代形式的(需要用到辅助栈),如下(partition 代码和递归形式的一模一样):

void quickSort(int arr[], int l, int h) 
{ 
    int stack[h - l + 1]; // Create an auxiliary stack
    int top = -1; // initialize top of stack
    stack[++top] = l; 
    stack[++top] = h; 

    while (top >= 0) { 
        h = stack[top--]; 
        l = stack[top--]; 
  
        // Set pivot element at its correct position in sorted array 
        int p = partition(arr, l, h); 
  
        // If there are elements on left side of pivot, then push them into stack 
        if (p - 1 > l) { 
            stack[++top] = l; 
            stack[++top] = p - 1; 
        } 
        // If there are elements on right side of pivot, then push them into stack 
        if (p + 1 < h) { 
            stack[++top] = p + 1; 
            stack[++top] = h; 
        } 
    } 
} 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值