基础排序之归并排序

来源:互联网 发布:python 并行计算 编辑:程序博客网 时间:2024/05/29 11:30
写了归并排序,以防以后需要。
</pre><pre name="code" class="cpp">#include "iostream"using namespace std;void MergeSort(int array[],int left,int mid , int right ,int temp[]){int i = left;int j = mid + 1;int MID = mid;int FIN = right;int k = 0;while(i <= MID && j <= FIN){if (array[i] <= array [j]){temp[k++] = array[i++];}else{temp[k++] = array[j++];}}while(i <= MID){temp[k++] = array[i++];}while(j <= FIN){temp[k++] = array[j++];}for (int i = 0; i < k; ++i){array[left + i] = temp[i];}}void Merge(int array[],int left,int right ,int temp[]){if (left < right){int mid  = (left +  right)/2;Merge(array,left,mid,temp);Merge(array,mid + 1,right,temp);MergeSort(array,left,mid,right,temp);}}bool ifMergeSort(int a[], int n)  {      int *p = new int[n];      if (p == NULL)          return false;      Merge(a, 0, n - 1, p);      return true;  } int main(int argc, char const *argv[]){int TestArray[] = {10,7,5,3,6};const int MAXNumber = 5;ifMergeSort(TestArray,MAXNumber);for (int i = 0; i < 5; ++i) { cout<<TestArray[i]<<endl; } return 0;}




0 0
原创粉丝点击