Note that there are some explanatory texts on larger screens.

plurals
  1. POproblems using MergeSorter in java
    text
    copied!<p>I am working on this MergeSorter but there is something that is not working and I cannot figure out. Any help is appreciated. Thank you. The problem most likely is in the sort method.</p> <pre><code>public class MergeSorter { private int[] a; /** Constructs a merge sorter. @param anArray the array to sort */ public MergeSorter(int[] anArray) { a = anArray; } /** Sorts the array managed by this merge sorter. */ public void sort() { int size = 1; int from = 0; int to = a.length - 1; // Complete this for the draft while (size &lt; to - from) { for (int i = 0; i&lt;=a.length; i=i+size*2) //for (int i = 0; i&lt;a.length; i=i+size*2) { if(a.length&gt;i+size*2-1){ merge(i, i+size-1, i+size*2-1); } else if(a.length&gt;i+size){ merge(i, i+size-1, a.length-1); } } size = 2 * size; } } public void merge(int from, int mid, int to) { System.out.println("Merging " + from + "..." + mid + " and " + (mid + 1) + "..." + to); // Complete this method for the final submission int iFirst = from; // Next element to consider in the first array int iSecond = mid+1; // Next element to consider in the second array int temp = 0; // As long as neither iFirst nor iSecond is past the end, move // the smaller element into a while (iFirst &lt;= mid &amp;&amp; iSecond &lt;= to) { if (a[iFirst] &lt; a[iSecond]) { iFirst++; } else if (a[iFirst] &gt; a[iSecond]) { temp = a[iFirst]; a[iFirst] = a[iSecond]; a[iSecond] = temp; iSecond++; } } } } </code></pre> <p>And this is my tester</p> <pre><code>public class test { public static void main(String[] args){ int[] a = {0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19}; MergeSorter m = new MergeSorter(a); m.sort(); for(int b : a){ System.out.print(b + " "); } } } </code></pre> <p>And this is the output, but the problem is in the last line the numbers are not consecutive. </p> <pre><code> Merging 0...0 and 1...1 Merging 2...2 and 3...3 Merging 4...4 and 5...5 Merging 6...6 and 7...7 Merging 8...8 and 9...9 Merging 10...10 and 11...11 Merging 12...12 and 13...13 Merging 14...14 and 15...15 Merging 16...16 and 17...17 Merging 18...18 and 19...19 Merging 0...1 and 2...3 Merging 4...5 and 6...7 Merging 8...9 and 10...11 Merging 12...13 and 14...15 Merging 16...17 and 18...19 Merging 0...3 and 4...7 Merging 8...11 and 12...15 Merging 0...7 and 8...15 Merging 0...15 and 16...19 0 1 2 3 4 5 6 7 8 9 12 13 14 15 16 17 10 11 18 19 Press any key to continue . . </code></pre> <p>I appreciate any help. Thank you</p>
 

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