void merge(int *p1_start, int *p2_start, int *end,int *copy) { int *p1 = p1_start; int *p2 = p2_start; int count =0; while(p1 < p2_start && p2 < end) { if(*p1 <= *p2) copy[count++] = *p1++; else copy[count++] = *p2++; } while(p1 < p2_start) copy[count++] = *p1++; while(p2 < end) copy[count++] = *p2++; int i; for(i = 0;i< count;i++) p1_start[i] = copy[i]; } /* * from bottom to top */ void merge_sort(int *begin, int *end, int *copy) { int len = end -begin; int step,j; for( step = 1;step < len ;step<<=1) { for (j = 0; (j+1)*step <= len; j+=2) { merge(begin+j*step,begin+(j+1)*step,begin+(j+2)*step,copy); } } } /** * from top to bottom */ void merge_sort(int *begin, int *end, int *copy) { if(end - begin == 1) return ; int len = end - begin; merge_sort(begin,begin+len/2,copy); merge_sort(begin+len/2,copy); merge(begin,begin+len/2,end,copy); }
归并排序—自底向上和自顶向下
最新推荐文章于 2022-02-27 10:18:26 发布