快速排序(递归与分治)

法一:

#include<cstdio>
#include<algorithm>
using namespace std;
int Partition(int A[],int left,int right){
	int i=left,j=right+1;//注意j=right+1
	int temp=A[left];
	while(true)
	{
		while(A[++i]<temp);
		while(A[--j]>temp);
		if(i>=j) break;
		swap(A[i],A[j]);
	 } 
	 swap(A[left],A[j]);
	 return j;
}
void quickSort(int A[],int left,int right){
	if(left<right){
		int pos=Partition(A,left,right);
		quickSort(A,left,pos-1);
		quickSort(A,pos+1,right);
	}
}
int main(){
	const int n=10;
	int A[n]={9,1,6,56,7,100,3,70,5,19};
	quickSort(A,0,n-1);
	for(int i=0;i<n;i++){
		printf("%d ",A[i]);
	}
	return 0;
}

法二:

#include<stdio.h>
int Partition(int A[],int left,int right){
	int temp=A[left];
	while(left<right){
		while(left<right&&A[right]>temp) right--;
		A[left]=A[right];
		while(left<right&&A[left]<=temp) left++;
		A[right]=A[left];
	}
	A[left]=temp;
	return left;
}
void quickSort(int A[],int left,int right){
	if(left<right){
		int pos=Partition(A,left,right);
		quickSort(A,left,pos-1);
		quickSort(A,pos+1,right);
	}
}
int main(){
	const int n=10;
	int A[n]={9,1,6,56,7,100,3,70,5,19};
	quickSort(A,0,n-1);
	for(int i=0;i<n;i++){
		printf("%d ",A[i]);
	}
	return 0;
}

 

 

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/Libra_69/article/details/85127614
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞