算法-快排

102 阅读1分钟
#include <iostream> 
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;
/*
Quick Sort
快速排序 
*/

int partition(int a[], int low, int high){
	int pivot = a[low];
	while(low < high){
		while(low < high && a[high] >= pivot){
			high--;
		}
		a[low] = a[high];
		while(low < high && a[low] <= pivot){
			low++;
		}
		a[high] = a[low];
	}
	a[low] = pivot;
	return low;
} 

void QuickSort(int a[], int low, int high){
	if(low < high){
		int pivotpos = partition(a, low, high);
		QuickSort(a, low, pivotpos-1);
		QuickSort(a, pivotpos+1, high);
	}
}

int main(){
	int arr1[100];
	//这里使用100个随机数
	int n = 100;
	for(int i = 0; i<n ;i++){
		arr1[i] = rand();
	} 

	cout<<"100个随机数为:"<<endl;
	for(int i = 0; i<n; i++){
		cout<<arr1[i]<<" ";
	}
	cout<<endl<<"100个随机数排序之后为:"<<endl;

	QuickSort(arr1, 0, 99);
	partition(arr1, 0, 99);
	
	

	for(int i = 0; i<n; i++){
		cout<<arr1[i]<<" ";
	}
}