C/C++ Quick Sort Algorithm

本文详细介绍了快速排序算法,包括其由来、基本策略和核心的划分(Partition)过程。在划分过程中,文章讨论了如何选取枢纽元以及不同方式对数组进行左右划分。同时,提到了内循环中使用`<`还是`<=`的思考,并指出在处理小数组时,插入排序可能更有效。最后,文章提及了递归(Recursive)操作在快速排序中的应用,并提供了代码运行示例。
摘要由CSDN通过智能技术生成


本系列文章由 @YhL_Leo 出品,转载请注明出处。
文章链接: http://blog.csdn.net/yhl_leo/article/details/50255069


快速排序算法,由C.A.R.Hoare于1962年提出,算法相当简单精炼,基本策略是随机分治。首先选取一个枢纽元(pivot),然后将数据划分成左右两部分,左边的大于(或等于)枢纽元,右边的小于(或等于枢纽元),最后递归处理左右两部分。分治算法一般分成三个部分:分解、解决以及合并。快排是就地排序,所以就不需要合并了。只需要划分(partition)和解决(递归)两个步骤。因为划分的结果决定递归的位置,所以Partition是整个算法的核心。快速排序最佳运行时间 O(nlogn) ,最坏运行时间 O(n

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! Here's an implementation of the Quick Sort algorithm in C++: ```cpp #include <iostream> #include <vector> // Function to partition the array and return the pivot index int partition(std::vector<int>& arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; std::swap(arr[i], arr[j]); } } std::swap(arr[i + 1], arr[high]); return i + 1; } // Function to perform quick sort recursively void quickSort(std::vector<int>& arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); quickSort(arr, low, pivotIndex - 1); quickSort(arr, pivotIndex + 1, high); } } int main() { std::vector<int> arr = {9, 5, 2, 7, 1, 8}; std::cout << "Array before sorting: "; for (int num : arr) { std::cout << num << " "; } quickSort(arr, 0, arr.size() - 1); std::cout << "\nArray after sorting: "; for (int num : arr) { std::cout << num << " "; } return 0; } ``` In this example, the `partition` function is used to choose a pivot element from the array and rearrange the elements such that all elements less than or equal to the pivot are on the left side, and all elements greater than the pivot are on the right side. The function returns the index of the pivot element. The `quickSort` function is a recursive function that repeatedly partitions the array and sorts the sub-arrays on either side of the pivot. The main function demonstrates the usage of the Quick Sort algorithm by creating a vector of integers, sorting it using `quickSort`, and then printing the sorted array. Note that this implementation uses the last element as the pivot. There are other variations of the Quick Sort algorithm that use different pivot selection strategies.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值