首先是归并排序,基本思想为分治,合并的技巧比较重要,不是原址排序。
代码如下;
int merge(int* x,int left,int mid,int right)
{
int i,j,k;
int L1 = mid-left+2;
int L2 = right-mid+1;
int* L = new int[L1];
int* R = new int[L2];
memcpy(L,x+left,sizeof(int)*L1);
memcpy(R,x+mid+1,sizeof(int)*L2);
L[L1-1] = INT_MAX;
R[L2-1] = INT_MAX;
i = j = 0;
k = left;
while(k <= right)
{
if(L[i] > R[j])
{
x[k++] = R[j++];
}
else
{
x[k++] = L[i++];
}
}
delete[] L;
delete[] R;
return 0;
}
int mergeSort(int* x,int left,int right)
{
if(left == right)
return 0;
int mid = (left+right)>>1;
mergeSort(x,left,mid);
mergeSort(x,mid+1,right);
merge(x,left,mid,right);
return 0;
}
快速排序,应用最广的排序算法,把一个数组分成两段,一段的数据比一个数小,另一段则比它大,再往下分治。
代码如下;
int quickPartition(int* x,int left,int right)
{
int k;
srand((unsigned int)time(NULL));
k = (rand()%(right-left+1))+left;
swap(x[k],x[right]);
k = left-1;
for(int i = left;i < right;i++)
{
if(x[i] <= x[right])
{
swap(x[++k],x[i]);
}
}
swap(x[++k],x[right]);
return k;
}
int quickSort(int* x,int left,int right)
{
if(left >= right)
{
return 0;
}
int mid = quickPartition(x,left,right);
quickSort(x,left,mid-1);
quickSort(x,mid+1,right);
return 0;
}
最大堆排序算法,仅作为排序应用较少,更多地作为优先队列使用。
代码如下:
int maxHeapify(int* x,int i,int L)
{
int large = i;
int l = i<<1;
int r = l+1;
if(l <= L&&x[l] > x[large])
{
large = l;
}
if(r <= L&&x[r] > x[large])
{
large = r;
}
if(large != i)
{
swap(x[large],x[i]);
maxHeapify(x,large,L);
}
return 0;
}
int buildMaxHeap(int* x,int L)
{
for(int i = L>>1;i >= 1;i--)
{
maxHeapify(x,i,L);
}
return 0;
}
int heapSort(int* x,int L)
{
buildMaxHeap(x,L);
for(int i = L;i >= 2;i--)
{
swap(x[1],x[i]);
maxHeapify(x,1,--L);
}
return 0;
}
原文地址:http://blog.csdn.net/dingzuoer/article/details/44276501