合并排序的基本思想是讲两个有序表合并。与其他排序算法不同的是,这个要占据额外的辅助空间。
void merge(int a[], int start, int end ,int mid, int*temp)
{
int i_start = start;
int i_end = mid;
int j_start = mid + 1;
int j_end = end;
int length = 0;
while(i_start <= i_end && j_start <= j_end)
{
if(a[i_start] < a[j_start]){
temp[length++] = a[i_start++];
}else{
temp[length++] = a[j_start++];
}
}
while(i_start <= i_end)
{
temp[length++] = a[i_start++];
}
while(j_start <= j_end)
{
temp[length++] = a[j_start++];
}
for(int i = 0; i<length;i++)
{
a[start+i] = temp[i];
}
}
void mergeSort(int a[], int start, int end , int*temp)
{
if(start>=end)
return;
int mid = (start+end)/2;
mergeSort(a, start, mid, temp);
mergeSort(a, mid+1, end, temp);
merge(a, start, end, mid, temp);
}
复杂度分析 合并排序 平均复杂度和最坏复杂度均为O(NlogN) 空间复杂度O(N)