java - Merge sort generic method -


my merge sort doesn't seem working correctly. when display sorted list, not sorted , elements added, there supposed 9 there 49. see im going wrong?

public static <e extends comparable<e>> void mergesort(list<e> a) {     int n = a.size();     if (n > 1) {         int half = n / 2;         list<e> b = copypartialarray(a, 0, half);         list<e> c = copypartialarray(a, half, n);         mergesort(b);         mergesort(c);         merge(b, c, a);     } }  public static <e extends comparable<e>> void merge(list<e> b, list<e> c, list<e> a) {     int n1 = b.size();     int n2 = c.size();     int = 0;     int j = 0;     int k = 0;     while (i < n1 && j < n2) {         if (b.get(i).compareto(c.get(j)) < 0) {             a.add(k, b.get(i));             i++;         }         else {             a.add(k, c.get(j));             j++;         }         k++;     }     if (i == n1)         (int p = j; p < n2; p++) {             a.add(k, c.get(p)); k++;         }     else if (j == n2)         (int p = i; p < n1; p++) {             a.add(k, b.get(p)); k++;         } }  private static <e extends comparable<e>> list<e> copypartialarray(list<e> a, int first, int last) {     int n = last - first;     list<e> copy = new arraylist<e>(n);     (int = 0; < n; i++)     copy.add(i, a.get(first + i));     return copy; } 

this answer try make realise what's wrong.

it's clear mergesort won't 1 element array, happens if there 2 (for instance [2,1])? mention there more elements before in result list (list a). why? what's merge doing list? hint.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -