1.MERGE: /** * MERGE two sorted arrays to the dest array * @param arrays the arrays to merge * @param p the start index in the first pile * @param q the end index in the first pile * @param r the end index in the second pile * return nil */ void MERGE(SortValue arrays[], int p, int q, int r) { //SENTINEL int max = 100000; int n1 = q - p + 1;//the length of the first int n2 = r - (q + 1) + 1;//the length of the second SortValue *L = (SortValue*) malloc(n1 + 2);//create L array SortValue *R = (SortValue*) malloc(n2 + 2);//create R array int i = 0; int j = 0; //copy to the left for (i = 0; i < n1; i++) { *(L + i) = arrays[p + i]; } //copy to the right for (j = 0; j < n2; j++) { *(R + j) = arrays[q + j + 1]; } //set sentinel *(L + n1) = &max; *(R + n2) = &max; i = 0; j = 0; int k; //sort,get the bigger one for (k = p; k < r + 1; k++) { if (int_compare(*(L + i), *(R + j)) <= 0) { *(arrays + k) = *(L + i); i = i + 1; } else { *(arrays + k) = *(R + j); j = j + 1; } } } 2.MERGE_SORT: /** * MERGE_SORT call MERGE * @param arrays the arrays to merge * @param p the start index in the first pile * @param r the end index in the second pile * return nil */ void MERGE_SORT(SortValue arrays[], int p, int r) { int q = 0; if (p < r) { q = (p + r) / 2; MERGE_SORT(arrays, p, q); MERGE_SORT(arrays, q + 1, r); MERGE(arrays, p, q, r); } }