交换排序---快速排序

快速排序: 是对起泡排序的一种改进。

  • 基本思想: 通过一次排序将序列分割成两个部分,一部分都比关键字大,一部分都比关键字小,进而继续对这两个子序列进行相同的操作。(通过递归)

  • 具体做法:每次可以将第一个元素设置为“分割元素temp”,附设两个指针,分别指向序列的头low和尾high。首先从high所指的位置向前查找第一个小于temp的元素与low所指的元素进行交换,然后从low所指的位置向前查找第一个大于temp的元素与high所指的元素进行交换,重复以上两步直至low==high。

  • 分析:时间复杂度为O(nlogn),空间复杂度为O(logn),为递归程序执行中,栈所需的辅助空间。该排序方法是稳定的
    在这里插入图片描述
    在这里插入图片描述

#include<iostream>
using namespace std;
void Qsort(int *a,int low,int high);//快速排序
int Partition(int *a,int low,int high);//求中间的位置 
void output(int *a,int length);//输出 
int main(){
	//int a[5]={3,4,5,2,1}; 
	int *a=new int;
	//a={3,4,5,2,1};
	for(int i=0;i<5;i++)
		cin>>a[i];
	Qsort(a,0,4);
	output(a,5);
}
int Partition(int *a,int s,int t){
	int low=s,high=t;
	int temp=a[s];
	while(low<high){
		while(low<high&&a[high]>temp)
			high--;
		a[low]=a[high];
		while(low<high&&a[low]<temp)
			low++;
		a[high]=a[low];
	}
	a[low]=temp;//将这个元素放到最终的位置 
	return low;
}
void Qsort(int *a,int s,int t){
	if(s<t){
		int flag=Partition(a,s,t);
		Qsort(a,s,flag-1);
		Qsort(a,flag+1,t);
	}
}
void output(int *a,int length){
	for(int i=0;i<length;i++)
		cout<<a[i]<<"  ";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值