排序——歸併排序
阿新 • • 發佈:2018-12-09
歸併排序:得到一個排序陣列,先把它們劃分為一個個有序的序列,再把每個有序的序列再一起歸併起來,著就是歸併排序。
程式碼如下:
void mergearray(int arr[], int start, int mid, int end, int tmp[])
{
int i = start;
int j = mid + 1;
int m = mid;
int n = end;
int k = 0;
while (i <= m && j <= n)
{
if (arr[i] <= arr[j])
tmp[k++] = arr[i];
else
tmp[k++] = arr[j];
}
while (i <= m)
{
tmp[k++] = arr[i++];
}
while (j <= n)
{
tmp[k++] = arr[j++];
}
for (int i = 0; i < k; i++)
{
arr[start + i] = tmp[i];
}
}
//遞迴版本
void mergeSort(int arr[], int start, int end, int tmp[])
{
if (start < end)
{
int mid = (start + end) / 2;
mergeSort(arr, start, mid, tmp);
mergeSort(arr, mid, end, tmp);
mergearray(arr, start, mid, end, tmp);
}
}
//非遞迴版本
void MergeSortNor(int* array, int size)
{
int gap = 1;
int* temp = (int*)malloc (sizeof(array[0])*size);
if(NULL == temp)
return;
while(gap < size)
{
int left, right, mid, i;
for(i = 0; i < size; i += 2*gap)
{
left = i;
mid = left + gap;
if(mid > size)
mid = size;
right = mid + gap;
if(right > size)
right = size;
MergeData(array, left, mid, right, temp);
}
memcpy(array, temp, size*sizeof(array[0]));
gap *= 2;
}
free(temp);
}
空間複雜度:O(n)
時間複雜度:O(n*lgn)
穩定性:穩定
適用場景:資料量比較大的場景