1. 程式人生 > >Various sorting algorithms 排序演算法總結分析

Various sorting algorithms 排序演算法總結分析

Contents

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)

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