归并排序

来源:互联网 发布:apache spark 修改数据 编辑:程序博客网 时间:2024/06/10 15:16

归并排序:将两个已经排好序的子序列合并成一个有序的序列。首先需要将整个序列进行分解,直到每个序列只有一个数(一个数必然有序),然后再合并。需要应用递归。

  • 时间复杂度:平均O(n*logn),最差O(n*logn)
  • 稳定性:稳定
代码实现:
//归并排序void merge(int *a, int start, int mid, int end) {int *temp =new int[end - start + 1];int i=start, j=mid+1, k=0;while (i <= mid&&j <= end) {if (a[i] <= a[j])temp[k++] = a[i++];elsetemp[k++] = a[j++];}while (i <= mid)temp[k++] = a[i++];while (j <= end)temp[k++] = a[j++];for (i = 0; i < k; i++)a[start + i] = temp[i];delete[]temp;}void mergeSort(int *a, int start, int end) {if (a == NULL || start >= end)return;int mid = (start + end) / 2;mergeSort(a, start, mid);mergeSort(a, mid + 1, end);merge(a, start, mid, end);}


原创粉丝点击