直接插入排序:直接插入排序是一種簡單的插入排序法,其基本思想是:把待排序的記錄按其關鍵碼值的大小逐個插入到一個已經排好序的有序序列中,直到所有的記錄插入完爲止,得到一個新的有序序列 。、
下圖是一個升序的排序過程
直接插入排序的特性總結:
- 元素集合越接近有序,直接插入排序算法的時間效率越高
- 時間複雜度:O(N^2)
- 空間複雜度:O(1),它是一種穩定的排序算法
- 穩定性:穩定
#include <vector>
//升序(用小於)
template<class T>
bool less(const T& x, const T& y)
{
return x < y;
}
//降序(用大於)
template<class T>
bool greater(const T& x, const T& y)
{
return x > y;
}
template<class T>
bool insertion_sorting(std::vector<T>& arr, bool(*t)(const T&, const T&))
{
if (arr.size() == 0)
{
return false;
}
for (int i = 1; i < (int)arr.size(); ++i) {
for (int j = i; j > 0; --j) {
if (t(arr[j], arr[j - 1])) {
T temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
return true;
}
int main()
{
std::vector<int> arr{ 3, 5, 8, 2, 54, 23, 57, 87, 1 };
std::vector<char> str{ 't', 'g', 'a', 'l', 'b' };
std::vector<double> arr1{ 2.1, 4.5, 1.2, 5.7, 78.7, 0.2 };
insertion_sorting(arr, greater<int>);
insertion_sorting(arr, less<int>);
insertion_sorting(str, greater<char>);
insertion_sorting(str, less<char>);
insertion_sorting(arr1, greater<double>);
insertion_sorting(arr1, less<double>);
return 0;
}