当前位置:网站首页>Quick sort

Quick sort

2022-07-24 20:30:00 To catty Hawthorn

/*
 Quick sort 
 thought , Divide and conquer , Select an element first , Make him reach the position where the final sorting is completed , here , His left element must 
 Smaller than him , The right side must be greater than , Then quickly arrange the arrays on both sides . 
*/

#include<iostream>
using namespace std;

void QuickSort(int a[],int s,int e)
{
	if(s >= e)	return;
	int i =s,j=e;
	int pivot = a[s];
	while(i != j){
		while(i < j && a[j] >= pivot) j--;	// Be careful , You need an equal sign , a[j] >= pivot, Or you won't get out  
		swap(a[i],a[j]);
		while(i < j && a[i] <= pivot) i++;
		swap(a[i],a[j]);
	}
	
	QuickSort(a,s,i-1);
	QuickSort(a,i+1,e);
} 

int main()
{
	int a[] = {93,27,30,2,8,12,2,8,30,89};
	int size = sizeof(a) / sizeof(int);
	QuickSort(a,0,size - 1);
	for(int i = 0;i < size;++i)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}

原网站

版权声明
本文为[To catty Hawthorn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207210514578319.html