#include <iostream>
using namespace std;
void main()
{
int arr[] = {5, 2, 4, 6, 1, 3};
const int len = sizeof arr/ sizeof arr[0];
cout << "原序列:";
for(int i=0; i<len; i++)
{
cout << arr[i] << ", ";
}
cout << endl;
//--插入排序(升序)----------------
for(int i=1; i<len; i++)
{
int key = arr[i];
int j = i-1;
while(j >= 0 && key < arr[j])
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
//---------------------------------
cout << "升序:";
for(int i=0; i<len; i++)
{
cout << arr[i] << ", ";
}
cout << endl;
//--插入排序(降序)----------------
for(int i=1; i<len; i++)
{
int key = arr[i];
int j = i-1;
while(j >= 0 && key > arr[j])
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
//---------------------------------
cout << "降序:";
for(int i=0; i<len; i++)
{
cout << arr[i] << ", ";
}
cout << endl;
}
运行结果:
原序列:5, 2, 4, 6, 1, 3,
升序:1, 2, 3, 4, 5, 6,
降序:6, 5, 4, 3, 2, 1,