Commit ea93fdef authored by xep's avatar xep
Browse files

2021.5.28 insert sort

parent e1ffae9f
......@@ -24,6 +24,26 @@ void quick_sort(T* x, int left, int right)
quick_sort(x, p + 1, right);
}
/// <summary>
/// 直接插入排序法标准实现,用来解决接近有序序列的情况
/// </summary>
template <typename T>
void insert_sort(T x[], int left, int right)
{
for (int i = left + 1; i < right; i++) {
if (x[i] < x[i - 1]) {
T tmp = std::move(x[i]);
int j = i-1;
while (j >= 0 && tmp < x[j]) {
x[j + 1] = std::move(x[j]);
j--;
}
//j最终指向要插入的前一个;j+1是空位
x[j + 1] = std::move(tmp);
}
}
}
#include <algorithm>
#include <time.h>
......@@ -38,10 +58,11 @@ int main()
for (int i = 0; i < N; i++) {
x[i] = rand() % 1000;
}
quick_sort(x, 0, N);
insert_sort(x, 0, N);
for (int i = 0; i < N; i++) {
cout << x[i] << ' ';
}
cout << endl;
cout << std::is_sorted(x, x + N) << endl;
return 0;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment