以下是各種排序算法的C++實(shí)現(xiàn),摘自《C++數(shù)據(jù)結(jié)構(gòu)與程序設(shè)計(jì)》,總結(jié)起來(lái)寫(xiě)成博客來(lái)用于溫習(xí)。
①插入排序
時(shí)間復(fù)雜度:O(n^2)。
優(yōu)點(diǎn):穩(wěn)定,快。
缺點(diǎn):比較次數(shù)不一定,比較次數(shù)越少,插入點(diǎn)后的數(shù)據(jù)移動(dòng)越多,特別是當(dāng)數(shù)據(jù)總量龐大的時(shí)候,但用鏈表可以解決這個(gè)問(wèn)題。
數(shù)組版實(shí)現(xiàn)如下:
//數(shù)組版template <class Record>void Sortable_list<Record>::insertion_sort() { int first_unsorted; int position; Record current; for (first_unsorted = 1; first_unsorted < count; first_unsorted++) { if (entry[first_unsorted] < entry[first_unsorted-1]) { position = first_unsorted; current = entry[first_unsorted]; do { entry[position] = entry[position-1]; position--; } while (position > 0 && entry[position-1] > current); entry[position] = current; } }}鏈?zhǔn)桨鎸?shí)現(xiàn)如下:
//鏈?zhǔn)桨鎡emplate <class Record>void Sortable_list<Record>::insertion_sort() { Node<Record>* first_unsorted, * last_sorted, * current, * trailing; if (head != NULL) { last_sorted = head; while (last_sorted-> next != NULL) { first_unsorted = last_sorted->next; if (first_unsorted->entry < head->entry) { last_sorted->next = first_unsorted->next; first_unsorted->next = head; head = first_unsorted; } else { trailing = head; current = trailing->next; while (first_unsorted->entry > current->entry) { trailing = current; current = trailing->next; } if (first_unsorted == current) last_sorted = first_unsorted; else { last_sorted->next = first_unsorted->next; first_unsorted->next = current; trailing->next = first_unsorted; } } } }}以上兩種版本的基本方法是一致的,僅有的真正的區(qū)別在于數(shù)組版本一逆序查找已排序的子表,而鏈?zhǔn)桨姹疽员碇形恢玫纳虿檎乙雅判虻淖颖怼?/p>②選擇排序
時(shí)間復(fù)雜度:O(n^2)。
優(yōu)點(diǎn):移動(dòng)數(shù)據(jù)的次數(shù)已知(n-1次)。
缺點(diǎn):比較次數(shù)多。
//順序?qū)崿F(xiàn)template <class Record>void Sortable_list<Record>::selection_sort() { for (int position = count-1; position > 0; position--) { int max = max_key(0, position); swap(max, position); }}template <class Record>void Sortable_list<Record>::max_key(int low, int high) { int largest, current;這種表中這種表中這種表中這種表中這種表中這種表中這種表中這種表中這種表中這種表中zhezhongbiaozhog largest = low; for (current = low+1; current <= high; current++) { if (entry[largest] < entry[current]) largest = current; } return largest;}template <class Record>void Sortable_list<Record>::swap(int low, int high) { Record temp; temp = entry[low]; entry[low] = entry[high]; entry[high] = temp;}選擇排序在每一趟都會(huì)至少將一個(gè)元素放在其最終位置上,從而使數(shù)據(jù)的移動(dòng)最少。這個(gè)算法主要對(duì)大元素的順序表有用,在這種表中移動(dòng)元素往往代價(jià)太大。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注