以下是各種排序算法的C++實現,摘自《C++數據結構與程序設計》,總結起來寫成博客來用于溫習。
①插入排序
時間復雜度:O(n^2)。
優點:穩定,快。
缺點:比較次數不一定,比較次數越少,插入點后的數據移動越多,特別是當數據總量龐大的時候,但用鏈表可以解決這個問題。
數組版實現如下:
//數組版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; } }}鏈式版實現如下:
//鏈式版template <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; } } } }}以上兩種版本的基本方法是一致的,僅有的真正的區別在于數組版本一逆序查找已排序的子表,而鏈式版本以表中位置的升序查找已排序的子表。②選擇排序
時間復雜度:O(n^2)。
優點:移動數據的次數已知(n-1次)。
缺點:比較次數多。
//順序實現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;}選擇排序在每一趟都會至少將一個元素放在其最終位置上,從而使數據的移動最少。這個算法主要對大元素的順序表有用,在這種表中移動元素往往代價太大。
新聞熱點
疑難解答