栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

快速排序算法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

快速排序算法

快速排序 1.概念和图解 1.1 概念简介

快速排序也称为分区交换排序,是对冒泡排序的改进。在快速排序中,通过分区间的一次每次交换能消除一个逆序。

1.2 算法思路
  1. 首先先选出一个中心轴(pivot),一般默认选择最左边的数,经过一次排序交换后,中心轴会将数分成两个子序,左边的数小于等于(升序时)中心轴,右边的数大于等于中心轴。
  2. 经过一次排序后,中心轴才会将数分成两边,然后再对两边的子序在进行排序交换,而后会发现可能子序还可能分成两个子序,我们重复的进行排序交换,到最后我们会发现,数已经排序好了。思路没有将具体的交换方式,下面例子会讲清楚, 这里只是能让你有一个简单了解。
1.3 例子图解

例子:用快速排序(升序)4, 2, 5, 88, 4,1

首先介绍一下第一轮排序交换发生了什么

2. 代码实现
#include 

template 
void print(const Type &arr, int size) //打印数组
{
    for (int i = 0; i < size; i++)
    {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}
//一趟快速排序,就是上面图的代码
template 
int partition(Type arr[], int low, int high) //快速排序
{
    Type tmp = arr[low]; //
    while (low != high)
    {
        while (low < high && tmp <= arr[high]) //先从右边开始移动
        {
            high--;
        }
        if (low < high) //如果还没相等,数值移动
        {
            arr[low] = arr[high];
            low++;
        }
        while (low < high && tmp >= arr[low]) //在右边移动一个,轮到左边移动一个
        {
            low++;
        }
        if (low < high)
        {
            arr[high] = arr[low];
            high--;
        }
    }
    arr[low] = tmp; //把中心抽放到分界处
    return low;     //返回中心轴
}
//递归快速排序,对子序分别再进行上图的操作
template 
void quickSort(Type arr[], int low, int high)
{
    int pivot; //中心轴位置
    if (low >= high)
    {
        return;
    }
    pivot = partition(arr, low, high);
    quickSort(arr, low, pivot - 1);  //中心轴左边
    quickSort(arr, pivot + 1, high); //中心轴右边
}
//快速排序的接口
template 
void quickSort(Type arr[], int size)
{
    quickSort(arr, 0, size - 1);
}
int main()
{
    int arr[] = {4, 2, 5, 88, 4,1};
    int count = sizeof(arr) / sizeof(arr[0]);
    quickSort(arr, count);
    print(arr, count);
    return 0;
}

3. 总结

就平均时间来说,快速排序是目前最好的内部排序算法,快速排序适用于记录较多且基本无序的情况下。因为排序过程中存在大胯度的的数据移动,所以快速排序以一种不稳定的排序方法。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955247.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号