java - Where did I make a mistake in the Mergesort algorithm -
java - Where did I make a mistake in the Mergesort algorithm -
i'm learning algorithm , @ moment seek implement mergesort java. code:
public class mergesort { /** * @param args */ public static void main(string[] args) { int []a = {12,34,6543,3,6,45,23,677,56,67,3,4,54,5}; sort(a); for(int i:a) { system.out.println(i); } } private static void merge(int[]a,int[]b,int[]c) { int = 0, j = 0, k = 0; while((i < b.length) && (j < c.length)) { if(b[i] < c[j]) { a[k++] = b[i++]; } else { a[k++] = c[j++]; } while( < b.length) { a[k++] = b[i++]; } while( j < c.length) { a[k++] = c[j++]; } } } public static void sort (int[]a) { if(a.length > 1) { int m = a.length / 2; int[]b = new int[m]; int[]c = new int[a.length-m]; for(int = 0; < m; i++) { b[i] = a[i]; } for(int = m; <a.length; i++ ) { c[i-m] = a[i]; } sort(b); sort(c); merge(a,b,c); } } }
this output:
6543 6 23 45 56 677 67 4 5 54
i re-create tutorial dont know error is. sec question is:
what mean: a[k++] == b[i++];
i know changing value of a[k] ( k = position in a) b[i] why ++?
i thought mean increasing value 1? give thanks reading.
your merge routine wrong. sec , 3rd while loops should not within first while loop. should outside it.
the first while loop compares items of 2 arrays until there no more elements left in 1 of them. after done, sec , 3rd loops should come play.
the sec , 3rd loops (only 1 of them work in invocation of merge) handle remainder of array contains highest values.
therefore should :
private static void merge(int[]a,int[]b,int[]c) { int = 0, j = 0, k = 0; while((i < b.length) && (j < c.length)) { if(b[i] < c[j]) { a[k++] = b[i++]; } else { a[k++] = c[j++]; } } while( < b.length) { a[k++] = b[i++]; } while( j < c.length) { a[k++] = c[j++]; } }
java algorithm
Comments
Post a Comment