二路归并排序
遞歸實現
時間復雜度:O(nlgn) 空間復雜度:O(1)http://m.blog.csdn.net/allen_fan_11/article/details/9097019
思路總結: (1)先遞歸分割 (2)再合并(把兩個有序數組進行排序合并)#include<stdio.h> void merge(int arr[], int l, int mid, int r) //合并 {int i = l;int j = mid + 1;int *t = new int[r - l + 1]; //開辟一個輔助數組tint k = 0;while (i <= mid && j <= r) //依次比較,取小值存入t[k]{if (arr[i] < arr[j]){t[k++] = arr[i++];}elset[k++] = arr[j++];}while (i <= mid) //當其中一個數組遍歷完成,把剩下的全部接過去{t[k++] = arr[i++];}while (j <= r){t[k++] = arr[j++];}for (k = l,i = 0; i < r - l + 1; i++) //把整個t數組拷貝給arr{arr[k] = t[i];k++;} }void MergeSort(int arr[], int l, int r) //遞歸分割 {if (l < r){int q = (l + r) / 2;MergeSort(arr, l, q);MergeSort(arr, q + 1, r);merge(arr, l, q, r);}}int main() {int arr[] = { 71, 61, 42, 8, 9, 3, 2 };//數組長度 = 數組元素的總個數int length = sizeof(arr) / sizeof(arr[0]);//傳入的l,r是數組的下標值,因此是0和length-1MergeSort(arr, 0, length - 1);for (int i = 0; i < length; i++)printf("%5d", arr[i]);printf("\n"); }總結
- 上一篇: 描述符:property 迭代器
- 下一篇: 插入排序,希尔排序