二分查找和快速排序(应该不能运行,只是一些笔记)

#include<iostream>
using namespace std;

template<class Type>
//二分查找
int BinarySearch(Type a[],const Type& x,int l,int r)
{//a[]排好的递增有序数组,x为要查找的数,l为第一个数,r为最后的数
	while(r>=1){//迭代查找
		int m=(l+r)/2;//二分查找
		if(x==a[m])return m;
		if(x<a[m])r=m-1;
		else l=m+1;
	}
	return -1;
}
//快速排序
template<class Type>
void QuickSort(Type a[],int p,int r)
{
	if(p<r){
		int q=Partition(a,p,r);
		QuickSort(a,p,q-1);//对左半段排序
		QuickSort(a,q+1,r);//对左半段排序
	}
}

template<class Type>
int Partition(Type a[],int p,int r)
{//r为最后一个数的数组下标,p为第一个数的数组下标
	
	int i=p,j=r+1;//这里r+1是因为后面,a[--j],而i没有-1是因为,这里是以第一数作为标准
	Type x=a[p];//x为划分的基准
	
	//将<x的元素交换到左边区域(两两交换)
	//将>x的元素交换到右边区域
	while(true){//利用这个大循环找到所有要交换的数和数组下标
		while(a[++i]<x);
		while(a[--j]>x);	//利用循环找到要交换的数和数组下标
		if(i>=j)break;     //跳出循环的条件
		Swap(a[i],a[j]);
	}
	a[p]=a[j];
	a[j]=x;
	return j;
}
template<class Type>
int Swap(Type a[i],Type a[j])
{
	Type temp;
	temp=a[i];
	a[i]=a[j];
	a[j]=temp;
}
int RandomizedPartition(Type a[],int p,int r)
{
	int i=Random(p,r);//随机产生基准
	Swap(a[i],a[p]);
	return Partition(a,p,r);
}
int main()
{

	return 0;
}



猜你喜欢

转载自blog.csdn.net/mtnhm123/article/details/80793713
今日推荐