Iterative mergesort in C++

我的梦境 提交于 2019-12-11 01:28:21

问题


i'm currently working on iterative version of mergesort, but i've encountered a problem. The program crashes when there are specific sizes of array's like 34,35,36 or 100(just few examples) and it works for the rest(fe works for powers of 2). I've ran some tests and debugged it, and the problem seems to be with the ranges of my iterations/left,right halves of mergesort, but i can't find it. I'll be thankful for your help. Code:

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
}

来源:https://stackoverflow.com/questions/36678841/iterative-mergesort-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!