合并排序C语言实现

来源:互联网 发布:js中foreach用法 编辑:程序博客网 时间:2024/05/17 20:25

include

include

include

define MAX_NUMBER 100

void OutPutData(int *piData, int iNoOfNumber)
{
int iTemp = 0;

if(piData == NULL || iNoOfNumber <= 0){    return;}printf("Total %d number:", iNoOfNumber);for(iTemp = 0; iTemp < iNoOfNumber; iTemp++){    printf("%d ", piData[iTemp]);}printf("\n");

}

void Merge(int *piData, int iBeginIndex, int iMidIndex, int iEndIndex)
{
int iLeftIndex = 0;
int iRightIndex = 0;
int iIndex = 0;
int *piLeftData = NULL;
int *piRightData = NULL;

do{    piLeftData = (int *)malloc((iMidIndex - iBeginIndex + 1) * sizeof(int));    if(NULL == piLeftData)    {        printf("===>[%s, %d]malloc failed!!!\n", __FUNCTION__, __LINE__);        break;    }    for(iIndex = 0; iIndex < iMidIndex - iBeginIndex + 1; iIndex++)    {        piLeftData[iIndex] = piData[iBeginIndex + iIndex];    }    piRightData = (int *)malloc((iEndIndex - iMidIndex) * sizeof(int));    if(NULL == piRightData)    {        printf("===>[%s, %d]malloc failed!!!\n", __FUNCTION__, __LINE__);        break;    }    for (iIndex = 0; iIndex < iEndIndex - iMidIndex; ++iIndex)    {        piRightData[iIndex] = piData[iMidIndex + 1 + iIndex];    }    iLeftIndex = 0;    iRightIndex = 0;    for(iIndex = 0; iIndex < iEndIndex - iBeginIndex + 1; iIndex++)    {        if(iLeftIndex < iMidIndex - iBeginIndex + 1 && iRightIndex < iEndIndex - iMidIndex)        {            if(piLeftData[iLeftIndex] < piRightData[iRightIndex])            {                piData[iBeginIndex + iIndex] = piLeftData[iLeftIndex];                iLeftIndex++;            }            else            {                piData[iBeginIndex + iIndex] = piRightData[iRightIndex];                iRightIndex++;            }        }        else        {            if(iLeftIndex < iMidIndex - iBeginIndex + 1)            {                piData[iBeginIndex + iIndex] = piLeftData[iLeftIndex];                iLeftIndex++;            }            if(iRightIndex < iEndIndex - iMidIndex)            {                piData[iBeginIndex + iIndex] = piRightData[iRightIndex];                iRightIndex++;            }        }    }}while(0);if(piLeftData){    free(piLeftData);    piLeftData = NULL;}if(piRightData){    free(piRightData);    piRightData = NULL;}

}

void MergeSort(int *piData, int iBeginIndex, int iEndIndex)
{
int iMidIndex = 0;

if(iBeginIndex < iEndIndex){    iMidIndex = (iBeginIndex + iEndIndex) / 2;    MergeSort(piData, iBeginIndex, iMidIndex);    MergeSort(piData, iMidIndex + 1, iEndIndex);    Merge(piData, iBeginIndex, iMidIndex, iEndIndex);}

}

int main(void)
{
int aiData[MAX_NUMBER];
int iTemp = 0;

setvbuf(stdout, NULL, _IONBF, 0);srand((unsigned int)(time(NULL)));for(iTemp = 0; iTemp < MAX_NUMBER; ++iTemp){    aiData[iTemp] = rand() % (MAX_NUMBER);}OutPutData(aiData, MAX_NUMBER);MergeSort(aiData, 0, MAX_NUMBER - 1);OutPutData(aiData, MAX_NUMBER);return EXIT_SUCCESS;

}

0 0