归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并
代码:
void mergearray(struct SQ_LIST *v, int first, int mid, int last, int temp[]) {
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n) {
if (v->elem[i].ID <= v->elem[j].ID)
temp[k++] = v->elem[i++].ID;
else
temp[k++] = v->elem[j++].ID;
}
while (i <= m)
temp[k++] = v->elem[i++].ID;
while (j <= n)
temp[k++] = v->elem[j++].ID;
for (i = 0; i < k; i++)
v->elem[first + i].ID = temp[i];
}
//排序
void mergesort(struct SQ_LIST *v, int first, int last, int temp[]) {
if (first < last) {
int mid = (first + last) / 2;
mergesort(v, first, mid, temp); //左
mergesort(v, mid + 1, last, temp); //右
mergearray(v, first, mid, last, temp); //再将二个有序数列合并
}
}
//归并排序主函数
void MergeSort(struct SQ_LIST *v, int n) {
int *p = new int[n];
mergesort(v, 0, n - 1, p);
delete[] p;
}