在实现MergeSort过程中出现的问题这里列一下,总结下来是对步骤没有详细的捋一遍,出现了边界和个数的不对应。
在C语言中的下标和个数的对应关系,以及如果要用其他语言编写的话要注意其中的对应的关系。
/*
208 * merge, merge two ordered subarray.
209 * p is first start-index as C, included,
210 * q is second start-index as C, included,
211 * r is the end-index of total as c, nonIncluded.
212 */
213 int mergeNonDec(int *a, int p, int q, int r)
214 {
215 int i = 0, j, k, *L=NULL, *R=NULL;
216 int n1 = q - p, n2 = r - q; // as the first longest bug: n1 = q - p + 1;
217 if(NULL == a || p>q || p>r || q>r){
218 return ERROR;
219 }
220 L = (int *)malloc((n1+1+1)*sizeof(int));
221 if(L == NULL){
222 return ERROR;
223 }
224 R = (int *)malloc((n2+1+1)*sizeof(int));
225 if(R == NULL){
226 free(L);
227 return ERROR;
228 }
229
230 for(i=0; i<n1; i++){
231 L[i] = a[p+i];
232 }
233 for(j=0; j<n2; j++){
234 R[j] = a[q+j];
235 }
236
237 L[n1] = INT_MAX;
238 R[n2] = INT_MAX;
239 i = j = 0;
240 for(k=p; k < r; k++){
241 if(L[i]<R[j]){
242 a[k] = L[i];
243 i++;
244 }
245 else{
246 a[k] = R[j];
247 j++;
248 }
249 }
250
251 free(L);
252 free(R);
253 return OK;
254 }