//直接插入排序是一种最简单的排序方法,它的基本操作是将一个记录插入到已排好的有序的表中,
//从而得到一个新的、记录数增1的有序表。
//当前元素的前面元素均为有序,要插入时,从当前元素的左边开始往前找(从后往前找),
//比当前元素大的元素均往右移一个位置,最后把当前元素放在它应该呆的位置就行了。
//复杂度:O(n^2)——插入排序不适合对于数据量比较大的排序应用
#include <iostream>
using namespace std;
template<typename DataType>
void output(DataType A[], int n) {
for(int i = 0; i < n; i++)
cout << A[i] << " ";
cout << endl;
}
template<typename DataType>
void InsertSort(DataType A[], int n)
{
DataType key;
int j;
int scanCnt = 0, swapCnt = 0;
for(int i = 1; i < n; i++)
{
key = A[i]; //当前i标号所对应的数组元素值---当前元素
j = i-1; //当前i前的元素标号j
while(j >= 0 && A[j] > key) //若j在合法范围(0~n-1)所指元素的值大于key
{
A[j+1] = A[j]; //将j所指元素放入j+1所指元素
j--; //将j前向移动,若持续当前元素比之前的小,则j一直变到0
}
A[j + 1] = key; //设置j+1所指元素值为key
output(A, n);
}
}
int main() {
int x[] = {7, 4, 6, 8, 3, 5, 1, 9, -2, 0};
cout << "初始状态: " << sizeof(x) / sizeof(int) << endl;
output(x, sizeof(x) / sizeof(int));
InsertSort<int>(x, sizeof(x) / sizeof(int));
return 0;
}
C++插入排序Demo程序
最新推荐文章于 2025-06-19 16:01:44 发布