Various sorting algorithms 排序算法總結分析


Updating…

Source Code

Source code on github

Overview

There exists so many kinds of sorting algorithms,e.g. bubble sort, quick sort, selection sort etc. However, many advanced sort algorithms are used in specific scenarios.

Different sort algorithm may use different datastructures, so it’s necessary to comprehend them, not only for learning algorithm, but also to master queue, stack,map , set etc.

Here, I’d like to show you the algorithm description , coding and testing , as a small but fully equipped project.

Algorithms below included:

  1. bubble sort

0-file I/O

  • If the input.txt file contains whitespace at the end of the file , the last element may be repeated.
  • How to handle the open-file-check code?

??

  • The concept of “stream” is important, stdio/file/string may be stream.

1-bubble sort

animation for bubble

algorithm description

每掃描一趟,將區間中最大的一個移至右側.

  • 改進:設置flag(sorted=true/false),如果本趟沒有進行交換操作,則說明左側已經是有序序列,無需再掃描.
  • 再改進:記錄最後一次交換的位置.
  • 總結:起泡排序無論怎麼改進,最壞情況依然是O(n2).
    最好情況(sorted): O(n), 平均複雜度O(n2), 低於O(nlogn)這一基於比較的排序算法下限.
    空間複雜度: O(1)

也可以從大到小排序,也可以從後向前冒泡。其特徵操作是相鄰元素的比較和交換

2-選擇排序selection

bubbleSort 在一輪掃描中總是盲目地交換,其實其中很多是不必要的.
Algorithm: 一趟掃描在n-i+1(i=1,2,3…,n-1)個記錄中選取關鍵字最小的記錄與第i個記錄交換,並作爲有序序列中的第i個記錄。

TIPs & Traps

不再使用for(i=0;i<?;i++) 之流, 畢竟寫c++就得專業些嘛!

  • 使用void swap( T& a, T& b ); 注意—交換的是value,不是iterator, i.e. 交換指針指向的值,不是pointer本身
int Sort::SelectSort(OutputDataType &sorted_data)
{
    size_t length = data_.size();
    sorted_data = data_;
    for (auto start_pos = sorted_data.begin(), end_pos = sorted_data.end(); end_pos != start_pos;)
    {
        //Finds the greatest element in the range [first, last).
        auto current_max = max_element(start_pos, end_pos);

        /**
         * Don't decrease end_pos twice.
         * FBI Warning: It's the value swapped, not the iterator!!! Or wrong!
         * swap(current_ma,--end_pos) ;  is totally wrong!!!!!!
         */
        swap(*current_max, *(--end_pos));
    }

    return 0;
}

  • 除了max_element(), 當然有min_element, 還有minmax_element 返回一個pair類型的(min,max), 類似python的tuple.
  • c++不像golang/python那樣可以簡潔地交換兩個元素的值,但是也不要總是temp=a;a=b;b=temp; or 使用exclusive來秀你的數電學得好~~~~庫函數swap() 在
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章