Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting An Array of Generic Type
    text
    copied!<p>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.</p> <p>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. </p> <pre><code>Input array: 5 1 -2 3 7 8 0 Output: -2 0 1 1 3 7 0 </code></pre> <p>Look like number 5 and 8 were somehow converted to different numbers during the sorting. Can someone show me why? Thanks!</p> <pre><code>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&lt;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&lt;=high; i++){// copy both parts into helper array helper[i] = array[i]; } int helperLeft = low; int helperRight = mid + 1; int current = low; while (helperLeft &lt;= mid &amp;&amp; helperRight &lt;=high){ if ((int)helper[helperLeft] &lt;= (int)helper[helperRight]){ array[current] = helper[helperLeft]; helperLeft++; } else{ array[current] = helper[helperRight]; helperRight++; } current++; } int remain = mid - helperLeft; for (int i=0; i&lt;remain; i++){ array[current+i] = helper[helperLeft + i]; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload