算法(1)插入排序
2017-11-30 16:00
232 查看
最近在看《算法导论》,想着将其中涉及到的算法都实现一遍,这是第一篇,也是刚刚开始。
插入排序的算法大致是这样的,好比打牌,将桌上的牌在手上实现排序。
1.从桌上拿一张牌
2.从后向前与手中的牌面大小进行比较。若相比更小,则说明还没有到插入的位置,手上的此牌右移一位。
3.若相比大,则插入到此牌的前一张。
4.重复1-3,直到桌面无牌为止。
代码实现如下
#include <iostream>
using namespace std;
void insert_sort(int *a,int len)
{
int temp,j;
for(int i=1;i<len;i++) //the remain card
{
temp=a[i];
for(j=i-1;j>=0;j--) //card in hand ,search from the back
{
if(temp<a[j])
a[j+1]=a[j]; //find? no,move
else
break; //find? yes.this a[j]>temp,so temp should be put in a[j+1]
}
a[j+1]=temp;
}
}
void show_array(int *a,int len)
{
cout<<endl;
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
int array[10]={2,6,1,44,22,7666,2,4,6,19};
show_array(array,10);
insert_sort(array,10);
show_array(array,10);
return 1;
}
插入排序的算法大致是这样的,好比打牌,将桌上的牌在手上实现排序。
1.从桌上拿一张牌
2.从后向前与手中的牌面大小进行比较。若相比更小,则说明还没有到插入的位置,手上的此牌右移一位。
3.若相比大,则插入到此牌的前一张。
4.重复1-3,直到桌面无牌为止。
代码实现如下
#include <iostream>
using namespace std;
void insert_sort(int *a,int len)
{
int temp,j;
for(int i=1;i<len;i++) //the remain card
{
temp=a[i];
for(j=i-1;j>=0;j--) //card in hand ,search from the back
{
if(temp<a[j])
a[j+1]=a[j]; //find? no,move
else
break; //find? yes.this a[j]>temp,so temp should be put in a[j+1]
}
a[j+1]=temp;
}
}
void show_array(int *a,int len)
{
cout<<endl;
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
int array[10]={2,6,1,44,22,7666,2,4,6,19};
show_array(array,10);
insert_sort(array,10);
show_array(array,10);
return 1;
}
相关文章推荐
- 白话经典算法系列之二 直接插入排序的三种实现
- 经典算法:二分查找、插入排序、选择排序、冒泡排序
- 白话经典算法系列之二 直接插入排序的三种实现
- 数据结构与算法二:插入排序
- 浅析各类排序算法(四) 插入类排序之直接插入排序及折半插入,2-路插入算法
- 算法不会,尚能饭否之排序——直接插入排序(Insert sort)
- 白话经典算法系列之二 直接插入排序的三种实现
- 算法--插入排序
- 白话经典算法系列之二 直接插入排序的三种实现
- 【算法】直接插入排序
- 算法-直接插入排序
- 白话经典算法系列之二 直接插入排序的三种实现
- 数据结构与算法——冒泡排序,选择排序,直接插入排序
- 第16周项目1-验证算法(1)直接插入排序 折半
- 算法学习 - 插入排序,希尔排序
- 算法入门--插入排序
- 排序算法(1)插入排序的算法分析
- 第十四周——项目一验证算法(3)插入排序之希尔排序
- 算法和数据结构---排序---插入排序
- 元素位置【算法】插入排序的递归实现