C++: quick sort(快排序)

本文介绍了快速排序算法,这是一种基于分治法的排序算法,时间复杂度为O(nlogn),且仅需O(logn)的额外空间。内容包括快速排序的工作原理、步骤、递归基例以及其在数组排序中的应用示例。
摘要由CSDN通过智能技术生成

到目前为止, 我们已经学习到了插入排序, 冒泡排序, 选择排序(selection)。 这些排序算法都是comparision based sorting algorithms(即涉及到元素大小的比较来决定元素的先后顺序)。 而且算法的时间复杂度上均为O(n^2)。但是comparision based 的排序算法远非这几个算法。 而且可以通过利用其它的一些手段(例如divide and conquer technique, 分治法)实现对基于比较的排序算法的时间复杂度降低到O(nlogn)。 其中一个就是quick sort, 故名思议, quick sort 的速度很快。

quick sort 可以采用一个in-place partition algorithm实现。quck sort 在递归的时候仅需要占用stack额外空间为O(logn)。

quick sort 是一个divide and conquer algorithms。 快排序通过首先对一个large array 分成2个小的subarrays: 即the low elements and the high elements。 Quick sort 可以recursively sort the subarrays。

快排序的步骤如下:

  1. Pick an element, called a pivot, from the array.
  2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position(也就是说, 这个pivot在其最后排好序的actual place). This is called the partition operation.
  3. Recursively apply the above steps to the sub-array of elements with smaller valu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值