sailing

Everything...

Merge Sort

// MergeSort.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <iostream>

 

void MergeSort(int* a, int iLen);

void MergePass(int* a, int* aa, int subLength, int iLen);

void Merge(int* a, int* aa, int start1, int end1, int start2, int end2);

void PrintArray(int a[], int iLen);

 

int _tmain(int argc, _TCHAR* argv[])

{

    int arrayToSort[] = {20, 7, 3, 4, 25, 15, 29, 12, 4, 1};

    int n = sizeof(arrayToSort)/sizeof(int);

    PrintArray(arrayToSort, n);

    MergeSort(arrayToSort, n);

    PrintArray(arrayToSort, n);

    return 0;

}

 

void MergeSort(int* a, int iLen)

{

    if(a==NULL||iLen<=0)

       return;

 

    int i=1;

    int* aa = (int*) new(int[iLen]);

    while(i<iLen)

    {

       MergePass(a,aa,i,iLen);

       i*=2;

       MergePass(aa,a,i,iLen);

       i*=2;

    }

    delete[] aa;

}

 

void MergePass(int* a, int* aa, int subLength, int iLen)

{

    int startIndex = 0;

    while(startIndex+2*subLength-1<iLen)

    {

      Merge(a,aa,startIndex,startIndex+subLength-1,startIndex+subLength,startIndex+subLength*2-1);

       startIndex=startIndex+2*subLength;

    }

    if(startIndex+subLength-1<iLen)

    {

       Merge(a,aa,startIndex,startIndex+subLength-1,startIndex+subLength,iLen);

    }

    else

    {

       while(startIndex<iLen)

       {

           aa[startIndex]=a[startIndex];

           startIndex++;

       }

    }

}

 

void Merge(int* a, int* aa, int start1, int end1, int start2, int end2)

{

    int i1= start1;

    int i2= start2;

    int i3= start1;

    while(i1<end1&&i2<end2)

    {

       if(a[i1]<a[i2])

       {

           aa[i3++]=a[i1++];

       }

       else

       {

           aa[i3++]=a[i2++];

       }

    }

    while(i1<=end1)

    {

       aa[i3++]=a[i1++];

    }

    while(i2<=end2)

    {

       aa[i3++]=a[i2++];

    }

}

 

void PrintArray(int a[], int iLen)

{

    for(int i=0; i< iLen; i++)

    {

       std::cout<<a[i]<<' ';

    }

    std::cout<<std::endl;

}

posted on 2007-01-29 01:11  乌生鱼汤  阅读(201)  评论(0编辑  收藏  举报

导航