java - Binary Insertion Sort in a similar fashion of regular Insertion Sort -
so i'm trying figure out how use binary insertion sort without need swap method or that. friend of mine gave me rough interpretation of necessary code can't seem want.
private static int binaryinsertionsort(int[] b) { int left, right, middle, i, m; int comparecount = 0; (int j = 1; j < b.length; j++) { left = b[j - 1]; right = b[j + 1]; if (b[j] < b[left]) { = left; } else { = left + 1; } m = b[j]; for(int k = 0; k < (j - - 1); k++) { b[j - k] = b[j - k - 1]; comparecount++; } b[i] = m; } return comparecount; }
the int comparecount merely see how many comparisons carried out on course of method. i'm trying arrange array of integers in regular fashion, b[0] = 1, b[1] = 2,...... b[63] = 64. in main method create array , assign values in reverse: b[0] = 64, b[1] = 63, etc. how can code rearrange them normal fashion seek? able normal insertion sort, little more......... tricky me.
nevermind. after tinkering , figuring out specific details friend, we've managed find out how this.
public static int binaryinsertionsort(int[] b) { int lo, mid, hi, temp; int comparecount = 0; (int = 1; < b.length; i++) { lo = 0; hi = i; mid = / 2; { if (b[i] > b[mid]) { lo = mid + 1; comparecount++; } else if (b[i] < b[mid]) { hi = mid; comparecount++; } else { comparecount++; break; } mid = lo + ((hi - lo) / 2); } while (lo < hi); if (mid < i) { temp = b[i]; (int j = - 1; j >= mid; j--) { b[j + 1] = b[j]; comparecount++; } b[mid] = temp; } } return comparecount; }
very tricky indeed, effort comes rewards. regardless no 1 answered, still thank viewed question.
Comments
Post a Comment