C++ 快速排序

快排分为两种,一种是双边循环法,另一种是单边循环法。

注意: 快排里的i与j下标比较时都要使用i < j,否则算法会错误!!!

(一)双边循环法:

#include<iostream>
using namespace std;

void QuickSort(int arr[],int l,int r);
void show(int arr[],int n);

int main(){
	int arr[10] = {213,42,13,53,1243,72,321,843,134,77};
	QuickSort(arr,0,9);
	show(arr,10);
	
	return 0;
} 

void show(int arr[],int n){
	for(int i=0;i<n;i++)
		cout<<arr[i]<<" ";
	cout<<endl;
}

void QuickSort(int arr[],int l,int r){//快速排序 
	if(l > r)
		return;
	int temp = arr[l];
	int i = l,j = r;
	while(i != j){
		while(j > i && arr[j] >= temp)//注意要判断j>i 
			j--;
		if(i < j){//注意要判断j>i 
			arr[i] = arr[j];
			i++;
		}
		
		while( j > i && arr[i] <= temp)//注意要判断j>i 
			i++;
		if(i < j){//注意要判断j>i 
			arr[j] = arr[i];
			j--;
		}
		
	}
	arr[i] = temp;
	QuickSort(arr,l,i-1);
	QuickSort(arr,i+1,r);
}

(二)单边循环法:

void sigleLoop(int[] array, int startIndex, int endIndex) {
	if(startIndex>=endIndex) {
		return;
	}
	int partition = partitionV2(array, startIndex, endIndex);
	sigleLoop(array, startIndex, partition-1);
	sigleLoop(array, partition+1, endIndex);
}
 
 
int partitionV2(int[] array, int startIndex, int endIndex) {
	int pivot = array[startIndex];
	int mark = startIndex;
	for(int i=startIndex+1; i<=endIndex; i++) {
		if(array[i]<pivot) {
			mark++;
			int temp = array[mark];
			array[mark] = array[i];
			array[i] = temp;
		}
	}
	array[startIndex] = array[mark];
	array[mark] = pivot;
	return mark;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值