1£©Ê²Ã´Êǹ鲢ÅÅÐò
¹é²¢ÅÅÐò£¨MERGE-SORT£©Êǽ¨Á¢Ôڹ鲢²Ù×÷ÉϵÄÒ»ÖÖÓÐЧµÄÅÅÐòËã·¨,¸ÃËã·¨ÊDzÉÓ÷ÖÖ稣¨Divide and Conquer£©µÄÒ»¸ö·Ç³£µäÐ͵ÄÓ¦Ó᣽«ÒÑÓÐÐòµÄ×ÓÐòÁкϲ¢£¬µÃµ½ÍêÈ«ÓÐÐòµÄÐòÁУ»¼´ÏÈʹÿ¸ö×ÓÐòÁÐÓÐÐò£¬ÔÙʹ×ÓÐòÁжμäÓÐÐò¡£Èô½«Á½¸öÓÐÐò±íºÏ²¢³ÉÒ»¸öÓÐÐò±í£¬³ÆΪ¶þ·¹é²¢¡£
2£©¹é²¢²Ù×÷(merge)£¬
Ò²½Ð¹é²¢Ëã·¨£¬Ö¸µÄÊǽ«Á½¸ö˳ÐòÐòÁкϲ¢³ÉÒ»¸ö˳ÐòÐòÁеķ½·¨¡£
Èç¡¡ÉèÓÐÊýÁÐ{6£¬202£¬100£¬301£¬38£¬8£¬1}
³õʼ״̬£º6,202,100,301,38,8£¬1
µÚÒ»´Î¹é²¢ºó£º{6,202},{100,301},{8,38},{1}£¬±È½Ï´ÎÊý£º3£»
µÚ¶þ´Î¹é²¢ºó£º{6,100,202,301}£¬{1,8,38}£¬±È½Ï´ÎÊý£º4£»
µÚÈý´Î¹é²¢ºó£º{1,6,8,38,100,202,301},±È½Ï´ÎÊý£º4£»
×ܵıȽϴÎÊýΪ£º3+4+4=11,£»
ÄæÐòÊýΪ14£»
3£©¹é²¢²Ù×÷µÄ¹¤×÷ÔÀí
µÚÒ»²½£ºÉêÇë¿Õ¼ä£¬Ê¹Æä´óСΪÁ½¸öÒѾÅÅÐòÐòÁÐÖ®ºÍ£¬¸Ã¿Õ¼äÓÃÀ´´æ·ÅºÏ²¢ºóµÄÐòÁÐ
µÚ¶þ²½£ºÉ趨Á½¸öÖ¸Õ룬×î³õλÖ÷ֱðΪÁ½¸öÒѾÅÅÐòÐòÁеÄÆðʼλÖÃ
µÚÈý²½£º±È½ÏÁ½¸öÖ¸ÕëËùÖ¸ÏòµÄÔªËØ£¬Ñ¡ÔñÏà¶ÔСµÄÔªËØ·ÅÈëµ½ºÏ²¢¿Õ¼ä£¬²¢Òƶ¯Ö¸Õëµ½ÏÂһλÖÃ
Öظ´²½Öè3Ö±µ½Ä³Ò»Ö¸Õ볬³öÐòÁÐβ
½«ÁíÒ»ÐòÁÐʣϵÄËùÓÐÔªËØÖ±½Ó¸´ÖƵ½ºÏ²¢ÐòÁÐβ
include <stdlib.h> #include <stdio.h>
void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex) { int i = startIndex, j=midIndex+1, k = startIndex; while(i!=midIndex+1 && j!=endIndex+1) { if(sourceArr[i] >= sourceArr[j]) tempArr[k++] = sourceArr[j++]; else tempArr[k++] = sourceArr[i++]; } while(i != midIndex+1) tempArr[k++] = sourceArr[i++]; while(j != endIndex+1) tempArr[k++] = sourceArr[j++]; for(i=startIndex; i<=endIndex; i++) sourceArr[i] = tempArr[i]; }
//ÄÚ²¿Ê¹Óõݹé void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex) { int midIndex; if(startIndex < endIndex) { midIndex = (startIndex + endIndex) / 2; MergeSort(sourceArr, tempArr, startIndex, midIndex); MergeSort(sourceArr, tempArr, midIndex+1, endIndex); Merge(sourceArr, tempArr, startIndex, midIndex, endIndex); } }
int main(int argc, char * argv[]) { int a[8] = {50, 10, 20, 30, 70, 40, 80, 60}; int i, b[8]; MergeSort(a, b, 0, 7); for(i=0; i<8; i++) printf("%d ", a[i]); printf("\n"); return 0; } |