插入排序伪代码:循环不定式的定义:
插入排序的循环不变式:
插入排序c++实现(正序)
#include<iostream>
using namespace std;
void Display(int array[],int length);
void InsertionSort(int array[],int length);
int main()
{
int a[10]={56,1,3,7,9,514,70,8,81,10};
Display(a,10);
cout<<endl<<"使用插入排序后";
InsertionSort(a,10);
Display(a,10);
system("pause");
return 0;
}
void Display(int array[],int length)
{
for(int a=0;a<length;a++)
{
cout<<"这是数组的第 "<<a<<"个元素:"<<array[a]<<endl;
}
}
void InsertionSort(int array[],int length)
{
for(int j=1;j<length;j++)
{
int key=array[j];
int i=j-1;
while(i>=0&&array[i]>key)
{
array[i+1]=array[i];
i--;
}
array[i+1]=key;
}
}
倒序:
#include<iostream>
using namespace std;
void Display(int array[],int length);
void InsertionSortDown(int array[],int length);
int main()
{
int a[10]={56,1,3,7,9,514,70,8,81,10};
Display(a,10);
cout<<endl<<"数组排序后的结果为";
InsertionSortDown(a,10);
Display(a,10);
system("pause");
return 0;
}
void Display(int array[],int length)
{
for(int a=0;a<length;a++)
{
cout<<"这是数组的第 "<<a<<"个元素:"<<array[a]<<endl;
}
}
void InsertionSortDown(int array[],int length)
{
for(int j=1;j<length;j++)
{
int key=array[j];
int i=j-1;
while(i>=0&&array[i]<key)
{
array[i+1]=array[i];
i--;
}
array[i+1]=key;
}
}