快速排序:
#include<iostream>
using namespace std;
int Partition(int *,int,int);
void QuickSort(int *r,int low,int high)
{
int pos;
if(low < high)
{
pos = Partition(r,low,high);
QuickSort(r,low,pos-1);
QuickSort(r,pos+1,high);
}
}
int Partition(int *r,int i,int j)
{
int pivotpos = r[i];
while(i<j)
{
while(i<j && r[j]>=pivotpos)
j--;
if(i<j)
r[i++] = r[j];
while(i<j && r[i]<=pivotpos)
i++;
if(i<j)
r[j--] = r[i];
}
r[i] = pivotpos;
return i;
}
冒泡排序:
void BubbleSort(int *r,int n)
{
int i,j;
bool exchange;
for(i=0;i<n-1;i++)
{
exchange = false;
for(j=0;j<n-i-1;j++)
{
if(r[j] > r[j+1])
{
int t = r[j];
r[j] = r[j+1];
r[j+1] = t;
exchange = true;
}
}
if(exchange == false)
return;
}
}
希尔排序:
void ShellSort(int *r,int len)
{
int d = len;
while(d>1)
{
d = (d+1)/2;
for(int i = 0;i<len-d;i++)
{
if(r[i] > r[i+d])
{
int temp = r[i];
r[i] = r[i+d];
r[i+d] = temp;
}
}
}
}
二分查找:
void BinarySearch(int r[],int n,int num){
int low,mid,high;
low = 0;
high = n-1;
while(low <= high)
{
mid = (low + high)/2;
if(r[mid] == num)
{
cout<<"找到"<<num<<",位置为:"<<mid+1<<endl;
break;
}else if(r[mid] < num)
{
low = mid +1;
}else
{
high = mid - 1;
}
}
cout<<"未能找到!"<<endl;
}