void merge(int srcarray[],int temparray[],int startindex,int midindex,int endindex) { int i = startindex,j = midindex + 1,k = startindex; while (i <= midindex && j <= endindex) { if(srcarray[i] > srcarray[j]) { temparray[k++] = srcarray[i++]; } else { temparray[k++] = srcarray[j++]; } } if(i <= midindex) { while(i <= midindex + 1) temparray[k++] = srcarray[i++]; } else { while(j <= endindex + 1) temparray[k++] = srcarray[j++]; } for(i = startindex;i <= endindex;i++) { srcarray[i] = temparray[i]; } } void mergesort(int srcarray[],int temparray[],int startindex,int endindex) { int midindex; if(startindex < endindex) { midindex = (startindex + endindex) / 2; mergesort(srcarray,temparray,startindex,midindex); mergesort(srcarray,temparray,midindex + 1,endindex); merge(srcarray,temparray,startindex,midindex,endindex); } }
原文地址:http://blog.csdn.net/llq108/article/details/44907847