归并排序的核心思想是将两个有序的数列合并成一个大的有序的序列。通过递归,层层合并,即为归并。效率为O(n log n),是分治法的典型应用。
/*
合并[left,mid),[mid,right)两个有序数组
*/
void merge(int *arry, int left, int mid, int right)
{int *temp = new int[right - left];int t = 0;int i = left;int j = mid;while (i < mid || j < right){if (i>= mid){temp[t++] = arry[j++];}else if (j>= right){temp[t++] = arry[i++];}else{if (arry[i] < arry[j]){temp[t++] = arry[i++];}else{temp[t++] = arry[j++];}}}t = 0;for (int i = left; i < right; i++){arry[i] = temp[t++];}delete[] temp;
}
/*
归并排序
算法主体
参数arry,数据数组
参数left,数组起始索引
参数right,数组末端索引
*/
void mysort(int *arry, int left, int right)
{if (left + 1 < right){int mid = (left + right) / 2;mysort(arry, left, mid);mysort(arry, mid, right);merge(arry, left, mid, right);}
}int main()
{const int count = 15;//测试数据个数int *arry = new int[count];srand(time(0));for (int i = 0; i < count; i++){arry[i] = rand() % 100;cout << arry[i] << endl;}cout << endl;mysort(arry, 0, count);//测试算法for (int i = 0; i < count; i++)//显示结果{cout << arry[i] << endl;}return 0;
}