Outline Sort Internal Sorting l l l Bubble
Outline Sort ¡ Internal Sorting ¡ l l l ¡ Bubble Sort Selection Sort Insertion Sort Quick Sort Heap Sort External Sorting l Merge Sort
Internal Sorting---Bubble Sort Example i=0 j=0 a[0] a[1] a[2] a[3] 5 26 81 j=1 5 26 81 7 63 j=2 5 26 7 81 j=3 5 26 7 a[0] a[1] a[2] i=2 7 a[4] 63 a[0] a[1] a[2] a[3] a[4] i=1 j=0 5 26 7 63 81 j=1 5 7 26 63 81 63 j=2 5 7 26 63 81 j=3 5 7 26 63 81 a[3] a[4] i=3 a[0] a[1] a[2] a[3] a[4] j=0 5 7 26 63 81 j=1 5 7 26 63 81 j=2 5 7 26 63 81 j=3 5 7 26 63 81
Selection Sort Example ¡ ¡ ¡ ¡ ¡ void select(char *string, int count) { int pos; /*目前最小的字元*/ int i, j; char temp; for ( i = 0; i < count - 1; i++ ) /*第一層迴圈, 執行交換*/ { pos = i; temp = string[pos]; for ( j = i + 1; j < count; j++ ) /*第二層迴圈, 找尋最小的字元*/ if ( string[j] < temp ) /*是否更小*/ { pos = j; /*新的最小字元*/ temp = string[j]; } string[pos] = string[i]; /*交換兩字元*/ string[i] = temp; printf("輸出結果: [%s]n", string); /*列印交換後字串 */ } }
Insertion Sort Example ¡ ¡ ¡ ¡ ¡ #include <stdlib. h> #define MAX 20 /*最大字串長度*/ void insert(char *string, int count) { int i, j; char temp; for ( i = 1; i < count; i++ ) /* 第一層迴路, 插入元素至字串中*/ { temp = string[i]; /*建立初值*/ j = i - 1; /*開始位置*/ /*空出插入位置, 將插入元素放在正確位置*/ while ( j >= 0 && temp < string[j] ) { string[j+1] = string[j]; j--; } string[j+1] = temp; /*插入字元*/ printf("輸出結果: [%s]n", string); /*列印交換後字串*/ } }
Quick Sort ¡ ¡ ¡ void q_sort(char *string, int left, int right) { char partition; /*分割元素*/ char temp; int i, j, k; temp= string[left]; /*若i>=j 則交換j與left的資料*/ string[left] = string[j]; string[j] = temp; printf("輸出結果: "); for ( k = left; k <= right; k++) /*列印處理字串 */ printf("%c", string[k]); printf("n"); /*換行*/ q_sort(string, left, j-1); /*遞迴呼叫處理第一部份*/ q_sort(string, j+1, right); /*遞迴呼叫處理第二部份*/ ¡ ¡ ¡ ¡ ¡ ¡ ¡ if ( left < right ) /*是否繼續分割*/ { i = left; /*分割的最左*/ j = right + 1; /*分割的最右*/ partition = string[left]; /*取第一個元素*/ do { /*從左往右找, 直到大於等於par才停止*/ i++; } while( string[i] < partition ); do { /*從右往左找, 直到小於等於par才停止*/ j--; } while( string[j] > partition ); if ( i < j ) { temp = string[i]; /*若有找到滿足前述兩 項條件者, 就交換資料*/ string[i] = string[j]; string[j] = temp; } } while( i < j ); ¡ ¡ ¡ } }
Quick Sort ¡ ¡ ¡ ¡ void quick(char *string, int n) { q_sort(string, 0, n-1); } void main() { char string[MAX]; /*字串陣列*/ int count; /*字串長度*/ printf("輸入欲排序的字串 ==> "); gets(string); /*讀取字串*/ count = strlen(string); /*計算字串長度*/ quick(string, count); /*快速排序法*/ /*列印排序後字串*/ printf("n輸出排序結果: [%s]n", string); }
Heap Sort Result
Merge Sort 1 2 3 5 4 6 7
Merge Sort 檔案1 1 4 5 6 1 2 3 4 檔案2 2 3 7 8
- Slides: 33