1. 程式人生 > >排序算法之歸並排序

排序算法之歸並排序

c數組 spa void 一個 使用 http image 二分 img

思路: 歸並排序使用了分治思想進行實現。對一個數組進行二分法,使用遞歸實現二分法。

       首先有一個數組C,可以將C數組分為A,B兩組,然後各自再把A,B分成二組。依次類推,當分出來的小組只有一個數據時,可以認為這個小組組內已經達到了有序,然後再合並相鄰的二個小組就可以了。

    這樣通過先遞歸的分解數列,再合並數列就完成了歸並排序。

      技術分享

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

template <typename T>
void
merge( T arr[], int iLeft, int iMid, int iRight ) { T temp[ iRight - iLeft + 1 ]; int k = 0; int i = iLeft, j = iMid + 1; while( i <= iMid && j <= iRight ) { if( arr[ i ] <= arr[ j ] ) { temp[k++] = arr[i++]; } else { temp[k
++] = arr[j++]; } } while( i <= iMid ) //對於左側有序數組中多余的元素進行插入 { temp[k++] = arr[i++]; } while( j <= iRight ) //對於右側有序數組中多余的元素進行插入 { temp[k++] = arr[j++]; } for( int l = 0; l < k; l++ ) { arr[iLeft+l] = temp[l]; } } template
<typename T> void mergeSort( T arr[], int iLeft, int iRight ) { if( iLeft >= iRight ) { return; } int mid = (iLeft + iRight)/2; mergeSort( arr, iLeft, mid ); mergeSort( arr, mid+1, iRight ); merge( arr, iLeft, mid, iRight ); } int main( ) { //setbuf(stdout,NULL); unsigned int pucBuff[10] = {3,4,1,7,3,7,8,9,4,0}; cout << "排序前\n" << endl; for( unsigned int i = 0; i < sizeof(pucBuff)/sizeof(int); i++ ) { cout << pucBuff[i] << " " ; } cout << endl; mergeSort( pucBuff, 0, sizeof(pucBuff)/4 -1 ); cout << "排序後\n" << endl; for( unsigned int i = 0; i < sizeof(pucBuff)/4; i++ ) { cout<< pucBuff[i]<< " "; } cout<<endl; return 1; }

排序算法之歸並排序