按分治法框架实现二分搜索
int BinarySearch(int A[],int n,int x)
{
int mid,t;
if(n<=0)
return -1;
else
{
mid=n/2;
if(A[mid]==x)
return mid;
else if(x<A[mid])
return BinarySearch(A,mid,x);//在前一半中搜索
else
{
t=BinarySearch(&A[n+mid+1],n-mid-1,x);//在后一半中搜索
return (t==-1)?-1:mid+1+t;
}
}
}
合并排序(归并排序(二路归并))
#include<stdio.h>
#define MAX 100
int B[MAX];
int MergeSort(int A[],int n){
//input:A to be sorted,the element number of A is n
//output:sorted,return 1;
if(n<=1)
return 1;
else{
MergeSort(A,n/2);//sort from 0 to n/2
MergeSort(A+n/2,n-n/2);//sort from n/2 to n
Merge(A,n);//merge
return 1;
}
}
int Merge(int A[],int n){
//input:the first half and the second half has been sorted,the element number is n
//output:sorted,return 1
int mid,s1,s2,i,b;
mid=n/2;//partition:A1[0:mid] and A2[mid:n],both of them are sorted
s1=0;//head of A1
s2=mid;//head of A2
b=0;
while(s1<mid&&s2<n){//transmit the smaller number from the two sub-Array to B Array respectively
if(A[s1]<=A[s2]){
B[b++]=A[s1++];
}
else{
B[b++]=A[s2++];
}
}
if(s1<mid){//transmit the surplus element of the former sub-Array to B Array
for(i=s1;i<mid;i++){
B[b++]=A[i];
}
}
else{//transmit the surplus element of the other sub-Array to B Array
for(i=s2;i<n;i++){
B[b++]=A[i];
}
}
for(i=0;i<n;i++){//depulicate B Array to A Array
A[i]=B[i];
}
return 1;
}
快速排序算法
#include<stdio.h>
int QuickSort(int A[],int n)
{
int p;
if(n<=1)
{
return 1;
}
else
{
p=Partition(A,n);
QuickSort(A,p);
QuickSort(A+p+1,n-p-1);
return 1;
}
}
int Partition(int A[],int n)
{
int low,high,x,p,i;
p=A[0];//记录主元pivot(也称枢轴)
x=0;//空位置
low=0;//低指针
high=n-1;//高指针
while(low<high){//指针从两头相对扫描,直到相遇
while(low<high&&A[high]>p)//从后向前寻找比主元p小的元素
high--;
if(low<high){
A[x]=A[high];
x=high;
}
while(low<high&&A[low]<=p)//从前向后寻找比主元p大的元素
low++;
if(low<high){
A[x]=A[low];
x=low;
}
}
A[x]=p;
return x;
}
随机选主元的快速排序
#include<stdio.h>
#include<stdlib.h>
int QuickSort(int A[],int n)
{
int p;
if(n<=1)
{
return 1;
}
else
{
p=Partition(A,n);
QuickSort(A,p);
QuickSort(A+p+1,n-p-1);
return 1;
}
}
int Partition(int A[],int n)
{
int low,high,x,p,i;
x=1.0*rand()/RAND_MAX*n;//随机挑选的主元位置
p=A[x];//记录主元pivot(也称枢轴)
A[x]=A[0];
x=0;
low=0;//低指针
high=n-1;//高指针
while(low<high){//指针从两头相对扫描,直到相遇
while(low<high&&A[high]>p)//从后向前寻找比主元p小的元素
high--;
if(low<high){
A[x]=A[high];
x=high;
}
while(low<high&&A[low]<=p)//从前向后寻找比主元p大的元素
low++;
if(low<high){
A[x]=A[low];
x=low;
}
}
A[x]=p;
return x;
}