1. 程式人生 > >二分查詢和快速排序(應該不能執行,只是一些筆記)

二分查詢和快速排序(應該不能執行,只是一些筆記)

#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;
}