描述: 在一個已經排好順序的序列內,要求插入一個新的元素之後新的序列還是一個有序的序列,這個時候就引入了插入排序,插入排序是一個穩定的排序方法,適用於對少量的數據進行排序。
時間複雜度:O(n^2)
思路:每步將一個待排序的元素,按其值的大小依次與前面排好的元素比較,然後插入到前面已經排序的數組中的適當位置上,直到全部插入排好爲止。
代碼:
由於給定的數組沒有已經排好順序的序列,所以最開始設置第二個元素爲待插入的元素,第一個元素爲一個有序的序列,兩者進行比較之後排好順序,之後再將第三個元素作爲待插入元素,依次類推…直到所有元素順序排完爲止。
- 對於insert_value你也可以理解爲一個 臨時變量 temp,目的是插入元素小於前一個元素時,用來交換兩個變量的值,這樣方便理解
// hmtian @ 2020/6/2 22:09
#include<iostream>
#include<vector>
int main()
{
std::vector<int> arr = {1,4,5,3,6,76,23,54,67,23,3};
for(int i = 1; i < arr.size(); i++)
{
//Because we dont know the order firstly, we set the second element as the insert_value.
int insert_value = arr[i];
//Obtain the element before insert_value for comparison.
int init_index = i-1;
while( init_index >= 0 && insert_value < arr[init_index])
{
arr[init_index + 1] = arr[init_index];
init_index--;
}
arr[init_index + 1] = insert_value;
}
for(const auto& e : arr){
std::cout << e <<" ";
}
std::cout<<std::endl;
}
結果:
參考自: 程序員必須掌握的那些算法