0
我已經寫了如下合併排序的代碼工作:歸併排序不是在所有情況下
#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 = 1
和n = 2
但不能爲其它的值。
錯字? 'int temp_b [n1];' - >'int temp_b [n2];' –
試着調試你的「mergeArray」。問題可能在那裏。 –
@WeatherVane謝謝你指出。但是代碼仍然不起作用。 – learner