今天写了一下插入排序,代码如下:
#include<iostream>
using namespace std;
void insertSort(int a[],int n){
int temp,j;
for (int i = 1; i < n; i++){
if (a[i] < a[i - 1]){
temp = a[i];
for (j = i - 1; (a[j] > temp)&&(j>=0); j--){
//将j位置的元素后移,temp插入到j+1
a[j + 1] = a[j];
}//for
a[j + 1] = temp;
}//if
}//for
}
void main()
{
int a[] = { 23, 2, 4, 42, 78, 1, 19, 1,34,22,34,45,6,7,8,99,24};
int len = sizeof(a) / sizeof(a[0]);
cout << "original sequence:" << endl;
for (int i = 0; i < len; i++){
cout << a[i] << " ";
}
cout << endl << endl;
insertSort(a,len);
cout << "the sequence of sorted:" << endl;
for (int i = 0; i < len; i++){
cout << a[i] << " ";
}
cout << endl << endl;
}