快速排序(二)

第二种快速排序,与快排(一)唯一不同的地方是Partition()函数,两者技巧不同,本质都一样都是实现一次快排。

// QuickSort2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
#include <ctime>

void QuickSort(int array[], int low, int high);
int Partition(int array[], int low, int high);
void Print(int array[], int length);

int _tmain(int argc, _TCHAR* argv[])
{
	srand((unsigned)time(NULL));//以时间为种子随机产生随机数
	int length=rand()%20;
	int *array=new int[length];//动态数组 
	for(int i=0;i<length;i++)
	{
		array[i]=rand()%100;
	}
	cout<<"Before quicksort,the array:"<<endl;
	Print(array,length);
	QuickSort(array,0,length-1);
	cout<<"Before quicksort,the array:"<<endl;
	Print(array,length);
	getchar();
	return 0;
}
void Print(int array[], int length)
{
	for (int i=0;i<length;i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
}
void QuickSort(int array[], int low, int high)
{
	int mid;
	if (low<high)
	{
		mid=Partition(array,low,high);
		QuickSort(array,low,mid-1);
		QuickSort(array,mid+1,high);
	}
}

int Partition(int array[], int low, int high)//与快速排序(一)唯一不同的地方 
{
	int flag=array[low];
	while(low<high)
	{
		while(low<high&&array[high]>=flag)
		{
			high--;
		}
		array[low]=array[high];
		while(low<high&&array[low]<=flag)
		{
			low++;
		}
		array[high]=array[low];
	}
	array[low]=flag;
	return low;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值