本文总结了包括简单选择排序、直接插入排序、冒泡排序、快速排序以及两路合并排序的算法(顺便把比较常用的二分搜索也写了)
//二分搜索递归
template <class T>
int BSearch(T& x,int *a,int low,int high)const
{
if(low<=high)
{
int mid=(low+high)/2;
if(x<a[mid])
return BSearch(x,a,low,m-1);
if(x>a[m-1])
return BSearch(x,a,m+1,high);
else
return m;
}
return -1;
}
return 0;
}
//二分搜索 迭代,适用于排序好的数组
int BSearch(int *arr,int &x)
{
int low=0,high=sizeof(arr)/sizeof(arr[0])-1,m;
while(low<=high)
{
m=(low+high)/2;
if(x>arr[m])
low=m+1;
else if(x<arr[m])
high=m-1;
else
return m;
}
return -1;
}
//简单选择排序
template <class T>
void SelectSort(T A[],int n)
{
int small;
for(int i=0;i<n-1;i++)
{
small=i;
for(int j=i+1;j<n;j++)
{
if(A[j]<A[small])
small=j;
}
swap(i,small);
}
}
//直接插入排序
//把当前元素直接插入到前面已经有序的序列中
template <class T>
void InsertSort(int A[],int n)
{
for(int i=1;i<n;i++)
{
int temp=A[i];
int j=i;
while(j>0&&temp<A[j])
{
A[j]=A[j-1];
j--;
}
A[j]=temp;
}
}
//冒泡排序,大的向上冒泡
template <class T>
void BubbleSort(T A[],int n)
{
int i,j,last;
i=n-1;
while(i>0)
{
last=0;//每次排序,如果不需要交换则last=0
for(j=0;j<last;j++)
{
if(A[j+1]<A[j])
swap(j+1,j);
last=j;
}
i=last;
}
}
template <class T>
void QuickSort(T a[],int n)
{
QSort(A,0,n-1);
}
template <class T>
void QSort(T A[],int left,int right)
{
int i,j;
if(left<right)
{
i=left;
j=right;
do{
do i++;while(A[i]>A[left]);
do j--;while(A[j]<A[left]);
if(i<j)
swap(i,j);
}while(i<j)
swap(left,j);
QSort(A,left,j-1);
QSort(A,j+1,right)
}
}
//两路合并排序
template <class T>
void Merge(T A[],int i1,int j1,int i2,int j2)//i1,j1,i2,j2分别是两个子序列的上下界
{
T *temp=new T[j2-i1+1];//分配能存放两个子序列大小的临时数组
int i=i1;int j=i2;int k=0;//i,j是两个子序列的游动指针,k是temp数组的游动指针
while(i<=j1&&j<=j2)//如果两个子序列都不为空,则循环
if(A[i]<A[j])//将A[i]和A[j]中比较小的放入temp数组
temp[k++]=A[i++];
else
temp[k++]=A[j++];
while(i<=j1) temp[k++]=A[i++];//将第一个子序列中剩余部分放入数组
while(j<=j2) temp[k++]=A[j++];//将第二个序列中剩余部分放入数组
for(i=0;i<k;i++)
A[i1++]=temp[i];//将临时数组中的元素放入A中
delete temp;
}
希望对大家有所帮助。