c++ 快速排序

 


快速排序


快速排序算法复杂度

快速排序的平均时间复杂度为O(n×log(n)),最糟糕时复杂度为O(n^2)


算法稳定性

不稳定。


c++ 实现代码

#include<iostream>
using namespace std;

void QuickSort(int* a, int low, int high);
int Partition(int* a, int low, int high);

int main()
{
	//int a[10] = {1,3,2,7,8,5,4,9,6,0};
	int a[10] = {1,2,3,4,5,6,7,8,9,0};
	int len = sizeof(a)/sizeof(a[0]);
	QuickSort(a,0,9);
	cout<<"after:"<<endl;
	for(int i=0;i<len;i++)
	{
		cout<<a[i]<<" ";
	}
	return 0;
}

void QuickSort(int* a, int low, int high)
{
    if (low < high)
    {
        int q = Partition(a, low, high);
		for(int i=0;i<10;i++)
		{
		cout<<a[i]<<" ";
		}
		cout<<endl;
        QuickSort(a, low, q - 1);
        QuickSort(a, q + 1, high);
    }
}

int Partition(int* a, int low, int high)
{
    int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分
    int i = low - 1;
    for (int j = low; j < high; j++) //遍历下标由low到high-1的数
    {
        if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数
        {
            int temp;
            i++;
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    //经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换
    a[high] = a[i + 1];
    a[i + 1] = x;
    return i + 1;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值