您的位置:首页 > 理论基础 > 数据结构算法

数据结构之插入排序

2015-12-16 19:12 302 查看
今天写了一下插入排序,代码如下:

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: