合并排序在所有情况下都不起作用

时间:2015-11-04 17:30:46

标签: c merge

我编写了以下用于合并排序的代码:

#include <stdio.h>

void mergeSort(int array[],int left, int right);

void mergeArray(int array[],int left,int middle, int right);

void mergeArray(int array[],int left,int middle, int right)
{

    int n1 = middle - left + 1;
    int n2 = right - middle ;

    int temp_a[n1];
    int temp_b[n2];

    int i = 0;
    int j = 0;
    int k = 0;

    for ( i = left ; i <= middle ; i++ )
    {
        temp_a[k++] = array[i];
    }

    for ( i = middle + 1 ; i < right + 1; i++ )
    {
        temp_b[j++] = array[i];
    }

    // now merge these two arrays


     i = 0;
     j = 0;
     k = 0;


    while ( i < n1 && j < n2 )
    {
        if ( temp_a[i] < temp_b[j])
        {
            array[k++] = temp_a[i++];

        }
        else
        {
            array[k++] = temp_b[j++];
        }
    }

    while ( i < n1 )
    {
        array[k++] = temp_a[i++];       
    }

    while ( j < n2 )
    {
        array[k++] = temp_b[j++];
    }



}


void mergeSort(int array[],int left, int right)
{
    // since there is only one element in the array.
    printf("I am in merge sort. left : %d, right : %d\n",left,right);
    if ( right - left < 1 )
    {
        return;
    }
    else
    {
        int middle = ( right - left ) / 2 ;
        mergeSort( array,left, middle );    
        mergeSort( array, middle +1 , right);

        mergeArray(array,left,middle,right);
    }


}

int main(int argc, char const *argv[])
{
    int n = 3;
    int i;

    int array[] = { 12,11,14,19};

    mergeSort(array,0,n);
    printf("\nArray is: \n");

    for (i = 0; i <= n; ++i)
    {
        printf("%d\n",array[i] );
    }
    return 0;
}

以上代码适用于n = 1n = 2,但不适用于其他值。

1 个答案:

答案 0 :(得分:1)

三个问题:(1)在mergeArray中,您使用n1代替n2 temp_b。将其更改为:

int temp_b[n2];

(2)创建temp_atemp_b后,在评论&#34;现在合并这两个数组&#34;后,您需要将k设置为{{1}而不是left

0

(3)在mergeSort中,k = left; 的表达式不正确,您需要添加而不是减去:

middle

它应该适用于这三个变化。