简体   繁体   中英

Sorting An Array of Generic Type

I am trying to implement Merge Sort algorithm on an array of genetic type. The problem is that the result is incorrect since some elements were set to 0. I suspect that the problem came from the casting I did through out the program, but I do not know exactly why.

As you can see in sortUsingMerge(), I casted an array of Object to generic. Also in the IF statement below, I casted the Object element in the array to int to be able to compare 2 elements. My intention is that the sorting algorithm should work for any array of any type, but I just do not want to write the Comparator for each type for now.

Input array: 5 1 -2 3 7 8 0
Output: -2 0 1 1 3 7 0

Look like number 5 and 8 were somehow converted to different numbers during the sorting. Can someone show me why? Thanks!

Source code:

public void sortUsingMerge(){
    Object[] array = (E[]) new Object[size];
    Object[] helper = (E[]) new Object[size];

    mergeSort(array,helper,0,size-1);

}
 public void mergeSort(Object[] array, Object[] helper, int low, int high){

       if (low<high){ 

            int mid = (low + high)/2;

            mergeSort(array,helper,low,mid); //sort left half
            mergeSort(array,helper,mid+1,high);//sort right half
            merge(array,helper,low,mid,high);

        }
}
public void merge(Object[] array, Object[] helper, int low, int mid, int high){

    for (int i=low; i<=high; i++){// copy both parts into helper array
        helper[i] = array[i];
    }

    int helperLeft = low;
    int helperRight = mid + 1;
    int current = low;

    while (helperLeft <= mid && helperRight <=high){

        if ((int)helper[helperLeft] <= (int)helper[helperRight]){
            array[current] = helper[helperLeft];
            helperLeft++;
        }
        else{
            array[current] = helper[helperRight];
            helperRight++;
        }

        current++;
    }


    int remain = mid - helperLeft;
    for (int i=0; i<remain; i++){
        array[current+i] = helper[helperLeft + i];
    }


}

inside merge replace

    for (int i=0; i<remain; i++){
     array[current+i] = helper[helperLeft + i];
    }

with

    while (helperLeft <= mid) {
        array[current] = helper[helperLeft];
        current++;
        helperLeft++;
    }

Casting would never give you that kind of error. You have bug at the end of your merge.

    int remain = mid - helperLeft;
    for (int i=0; i <= remain; i++) {                 //changed < to <=
        array[current+i] = helper[helperLeft + i];
    }

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