1. 程式人生 > >八種排序方法(七)——歸併排序

八種排序方法(七)——歸併排序

編譯器:Xcode
程式語言:C++

源程式:

#include<iostream>
using namespace std;

void merge(int a[],int low,int mid,int high)
{
    int i,k;
    //定義一個臨時陣列存放傳進來的無序陣列排好序之後的陣列
    int *temp=(int *)malloc((high-low+1)*sizeof(int));
    //將無序陣列分成兩個序列
    int left_low=low;
    int left_high=mid;
    int right_low=mid+1
; int right_high=high; //將兩個序列比較排序,小的排前 for(k=0;left_low<=left_high && right_low<=right_high;k++) { if(a[left_low]<=a[right_low]) temp[k]=a[left_low++]; else temp[k]=a[right_low++]; } //左序列如果有剩下元素未排序,加到臨時陣列的末尾 if(left_low<=left_high) { for
(i=left_low;i<=left_high;i++) temp[k++]=a[i]; } //右序列如果有剩下元素未排序,加到臨時陣列的末尾 if(right_low<=right_high) { for(i=right_low;i<=right_high;i++) temp[k++]=a[i]; } //將排好序的小分組轉移到原陣列中 for(i=0;i<high-low+1;i++) { a[low+i]=temp[i]; } free
(temp); } void mergeSort(int a[],int first,int last)//歸併排序 { int mid=0; //將陣列不停的二分分組再組合,直到每組只剩下一個元素 if(first<last) { mid=(first+last)/2; mergeSort(a, first, mid); mergeSort(a, mid+1, last); merge(a,first,mid,last); } } int main() { int a[10] = {43, 65, 4, 23, 6, 98, 2, 65, 7, 79}; cout<<"歸併排序:"<<endl; mergeSort(a, 0, 9); for(int i=0;i<10;i++) cout<<a[i]<<" "; cout<<endl; return 0; }

執行結果:

歸併排序:
2 4 6 7 23 43 65 65 79 98 
Program ended with exit code: 0