版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36503007/article/details/80275759
//插入排序法比较简单,就只贴上代码和运行结果
//升序排列和降序排列都写了一遍,基本是一样
【代码】
#include <iostream>
using namespace std;
int main()
{
int n, *a;
cout << "请输入乱序数字的个数:";
cin >> n;
//------------------------------------------------------------------
a = new int[n];
cout << "乱序数字分别为:" << endl;
for (int i = 0; i < n; i++)
cin >> a[i];
int t = 0;//用来存放待插数字a[j]
/****************************降序排列*******************************/
for (int j = 1; j < n; j++)//外循环控制插入次数,插入次数共n-1次,并从a[1]即第二个数字开始作为待插数字
{
t = a[j];
int i = j - 1;
while (i >= 0 && a[i] < t)//内循环寻找待插数字的插入位置
{
a[i + 1] = a[i];
a[i] = t;
i--;
}
}
cout << "按降序排列:" << endl;
for (int i = 0; i < n; i++)
cout << a[i] << " ";
//----------------------------------------------------------------------
cout << "\n\n";
//-----------------------------------------------------------------------
/*******************************升序排列********************************/
for (int j = 1; j < n; j++)
{
t = a[j];
int i = j - 1;
while (i >= 0 && a[i] > t)
{
a[i + 1] = a[i];
a[i] = t;
i--;
}
}
cout << "按升序排列:" << endl;
for (int i = 0; i < n; i++)
cout << a[i] << " ";
//-----------------------------------------------------------------------
delete[]a;//new之后一定要delete
system("pause");
return 0;
}
【运行结果】