C ++中的迭代合并

时间:2016-04-17 16:02:16

标签: c++ sorting iteration mergesort

我目前正在研究mergesort的迭代版本,但我遇到了一个问题。当阵列的特定大小如34,35,36或100(只是几个例子)时,程序崩溃,并且它适用于其余的(fe适用于2的幂)。我已经运行了一些测试并对其进行了调试,问题似乎在于我的迭代范围/左侧,右侧的mergesort,但我无法找到它。我会感谢你的帮助。 代码:

int * loadArray(int size){ //i input size of array and it assigns random numbers
    int *array = new int[size];

     srand( time( NULL ) );

    for( int i = 0; i < size; i++ )
        array[i]=rand()%100;

    return array;
}




void merge(int arr[], int left, int middle, int right)
{
    int i, j, k;              //iterators
    int n1 = middle-left + 1; //indexes
    int n2 = right-middle;    //indexes
    int Left[n1], Right[n2];  //arrays holding halves

for (i = 0; i < n1; i++)
    Left[i] = arr[left + i];//assigning values to left half
for (j = 0; j < n2; j++)
    Right[j] = arr[middle + 1+ j];//assigning values to right half

i = 0;
j = 0;
k = left;
while (i < n1 && j < n2)    //comparing and merging
{
    if (Left[i] <= Right[j])
    {
        arr[k] = Left[i];
        i++;
    }
    else
    {
        arr[k] = Right[j];
        j++;
    }
    k++;
}

while (i < n1)  //leftovers
{
    arr[k] = Left[i];
    i++;
    k++;
}

while (j < n2)  //leftovers
{
    arr[k] = Right[j];
    j++;
    k++;
}
}




void mergeSortIter(int array[], int size) //the function which is being called and handles division of the array
{
    double startTime = clock(); //start measuring time

    int i;
    int left_start;

   for (i=1; i<=size-1; i = 2*i)
   {
       for (left_start=0; left_start<size-1; left_start += 2*i)
       {
            int mid = left_start + i - 1;
            int right_end = min(left_start + 2*i - 1, size-1);
            merge(array, left_start, mid, right_end);
       }
       //showArray(array,size);
   }
    cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl; //output the time measured
}

0 个答案:

没有答案