#include<iostream>
using namespace std;
#define M 11
void InsertSort(int a[])
{
cout << "排序过程: " << endl;
int temp;//临时变量
int i, j;//循环变量
for (i = 1; i < M; i++)
{
temp = a[i];//获取比较值
for (j = i; j>0 && a[j - 1] > temp; j--)//前i个元素,如果有大元素交换
a[j] = a[j - 1]; //移到当前位置
a[j] = temp;//将最后一个交换的j位置元素赋值temp
for (int k = 0; k < M; k++)
cout << a[k] << " ";
cout << endl;
}
}
void main()
{
cout << "----------------插入排序---------------" << endl;
int a[M] = { 0, 209, 386, 768, 185, 247, 606, 230, 835, 54, 12 };
cout << "排序之前的元素为: \n";
for (int i = 0; i < M; i++)//循环排序前数组
cout << a[i] << " ";
cout << endl;
InsertSort(a); //插入排序法
cout << "排序结果为:\n";
for (int i = 0; i < M; i++)//循环排序后数组
cout << a[i] << " ";
cout << endl;
}插入排序
最新推荐文章于 2022-10-25 20:09:27 发布
4万+

被折叠的 条评论
为什么被折叠?



