running issue mergesort. after sort array, want print sorted array, not every pass. code below. running printarray(intarray) after array seems sorted. maybe putting in wrong spot? can see in mergesortcomparisons function @ end.
private static int merge(int[] intarray, int first, int n1, int n2) { int[] temp = new int[n1+n2]; int copied = 0, copied1 = 0, copied2 = 0; while((copied1 < n1) && (copied2 < n2)){ if (intarray[first + copied1] < intarray[first + n1 + copied2]) temp[copied++] = intarray[first + copied1++]; else temp[copied++] = intarray[first + n1 + copied2++]; } while(copied1 < n1) temp[copied++] = intarray[first + copied1++]; while(copied2 < n2) temp[copied++] = intarray[first + n1 +copied2++]; for(int = 0; < n1+n2; i++) { numcomparisons++; intarray[first + i] = temp[i]; } return first; } public static int mergesortcomparisons(int[] intarray, int first, int last){ int n1, n2; if (last > 1){ n1 = last/2; n2 = last - n1; mergesortcomparisons(intarray, first, n1); mergesortcomparisons(intarray, first + n1, n2); merge(intarray, first, n1, n2); } printarray(intarray); return numcomparisons; }
since calling mergesortcomparisons recursively call printarray happens on every pass after every merge. if return intarray mergesortcomparisons method code called should able call printarray there , it'll execute once.
Comments
Post a Comment