归并排序C++实现
歸并排序的核心思想是將兩個有序的數列合并成一個大的有序的序列。通過遞歸,層層合并,即為歸并。效率為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; }總結
- 上一篇: 照相机的成像变换
- 下一篇: 进入opencv内部函数调试