简体   繁体   中英

Merge sort not sorting self created array class c++

my merge sort method dont work how i want to, ive created Array Class with some custom methods and tried to create proper components to merge sort work. result is that the returned table is filled with zeros and random numbers and it is being filled till memory is full. Please if You could give me some tips to waht i should pay attention to fix it.

also full Array Class if You want to look at it here : https://codeshare.io/5Xnk9Y

thanks in advance for any help.

Array Array::merge(Array left, Array right, Array mergedArray)
{   
    int i,j,k,nL,nR;
    i=j=k=0;
    nL = left.GetNumberOfElements();
    nR = right.GetNumberOfElements();
    while(i < nL && j < nR)
    {
        if (left.GetElementWithIndex(i) <= right.GetElementWithIndex(j))
        {   
            mergedArray.SetElementWithIndex(k, left.GetElementWithIndex(i));
            i++;
            k++;
        }else 
        {
            mergedArray.SetElementWithIndex(k, right.GetElementWithIndex(j));
            k++;
            j++;
        }       
    }
    while (i < nL){
        mergedArray.SetElementWithIndex(k,left.GetElementWithIndex(i));

        i++;
        k++;
    }
    while (j < nR){
        mergedArray.SetElementWithIndex(k, right.GetElementWithIndex(j));
        j++;
        k++;
    }
    return mergedArray;
}

Array Array::splitArrayForMergeSort(Array splitedArray)
{
    int length;
    length = splitedArray.GetNumberOfElements();
    if(length < 2) return splitedArray;

    int middle;


    if(length %2 == 1) middle = (length-1)/2;
    else middle = length/2;


    Array left;
    Array right;

    for (int i = 0 ; i < middle ; i++){
        left.AddElement(splitedArray[i]);
    }
    for (int i = middle ; i < length ; i++){
        right.AddElement(splitedArray[i]);
    }

    splitArrayForMergeSort(left);
    splitArrayForMergeSort(right);
    merge(left, right, splitedArray);
}

void Array::MergeSort()
{
    Array arr;
    for (int i = 0 ; i < numberOfElements ; i++){
        arr.AddElement(array[i]);
    }   
    arr = splitArrayForMergeSort(arr);
}

谢谢我忘了在splitArrayForMergeSort()方法的末尾返回splitedArray ,添加splitArrayForMergeSort()之后,一切正常,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM