数据结构之插入排序
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;
}
#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;
}
相关文章推荐
- 2015年大二上-数据结构-数组与广义表(2)-4.下三角矩阵的压缩存储及基本运算
- 2015年大二上-数据结构-数组与广义表(2)-3.上三角矩阵的压缩存储及基本运算
- 一、redis 数据结构使用场景
- Redis学习笔记~Redis提供的五种数据结构
- 软考数据库-数据结构
- 数据结构期末总结——既然选择了远方 便只顾风雨兼程
- 基础数据结构之数组与链表(一)
- 数据结构
- .Net数据结构:DictionaryBase DictionaryEntry Hashtable
- Java数据结构——LinkedList源码简介
- JavaScript(4) - JS数据结构和算法 1
- 数据结构(C语言)全程更新第一版震撼来袭
- 树状数组学习笔记
- 数据结构与算法
- 数据结构和算法经典100题-第21题
- 数据结构C++语言描述专题系列 (五) 递归
- 直接插入排序,快速排序,选择排序给学生成绩排名
- 数据结构 上机测试题 汇总
- <LeetCode OJ> (1 / 15 / 16 / 18) NSum问题集合
- MySQL索引背后的数据结构及算法原理