c++ - How to find the low & high in Merge Sort -
i have basic understanding of merge sort algorithm. reason can't wrap head around values low , high coming from. code working merge.
void practicemerge(int a[], int low, int mid, int high) { int b[10000]; int = low, j = mid + 1, k = 0; while (i <= mid && j <= high) { if (a[i] <= a[j]) b[k++] = a[i++]; else b[k++] = a[j++]; } while (i <= mid) b[k++] = a[i++]; while (j <= high) b[k++] = a[j++]; k--; while (k >= 0) { a[low + k] = b[k]; k--; } }
let me explain commenting code:
//sort array index low index high merging 2 //subarrays of go low mid , mid high. void practicemerge(int a[], int low, int mid, int high) { int b[10000]; //buffer int = low; //starting index in first sub array int j = mid + 1; //starting index in second sub array int k = 0; //starting index in buffer //while not go beyond limit of first subarray //nor second while (i <= mid && j <= high) { if (a[i] <= a[j]) //put value of first subarray, , move b[k++] = a[i++]; else //put value of first subarray, , move b[k++] = a[j++]; } //finish copying first subarray if not done yet while (i <= mid) b[k++] = a[i++]; //finish copying second subarray if not done yet while (j <= high) b[k++] = a[j++]; //copy buffer array k--; while (k >= 0) { a[low + k] = b[k]; k--; } }
basically, low, mid , high, borders of array "a" looking at. "a" bigger. ex:
a = 3 2 1 5 6 7 0 1 low = 0 mid = 2 high = 4
here sorting first half of a.
edit: function merges arrays. main merge sort function, splits array. be:
void merge_sort(int a[], int lo, int hi) { if (low >= hi) return; //nothing sort int mid = (lo+hi)/2; //the guy between lo , hi. merge_sort(a,lo, mid); //sort left merge_sort(a, mid, hi); //sort right practicemerge(a, lo, mid, hi); //this merges array }
to understand (don't copy paste!) think of way: merge_sort sorts chunk of array, not entire array, bit between lo , hi. in order so, sorts 1 half, other. merges result array. therefore, inside merge_sort, "hi" , "lo" computed parameter. now, you, user, might want sort array 0 end, or 10th 99th index. choice. , parameters pass call.
void main() { //bla bla bla merge_sort(songs, 89, 250); //only sort songs }
think of this, black box. call parameters, box thing. because box uses itself, knows how call (i.e. know how compute low, high , mid) initial call in recursion responsability user.
p.s.: feel im not being clear...
Comments
Post a Comment