白话经典算法系列之二 直接插入排序的三种实现(转)

来源:互联网 发布:巨灵数据 金融界 编辑:程序博客网 时间:2024/05/16 15:01

http://blog.csdn.net/morewindows/article/details/6665714

#include<iostream>using namespace std;//交换两个数,这里用到了引用void Swap(int &a, int &b){    int temp;    temp = a;    a = b;    b = temp;    return ;}void Insertion_Sort2(int a[], int len){    int i,j;    int temp;    for (i = 1; i < len ;i++)    {        if (a[i-1] > a[i])    //判断是否需要调整        {            temp = a[i];            for(j = i -1; j >=0&& a[j]>temp; j--)            {                a[j + 1] = a[j];            }            a[j +1] = temp;     //加1补回来        }    }    return ;}void Insertion_Sort1(int a[], int len){    int i, j, k;    int temp;    for(i = 1; i < len ; i++)    {        //为a[i]在前面的a[0...i-1]有序区间中找到合适的位置        for(j = i -1; j >=0; j--)        {            if(a[j] > a[j +1])            {                Swap(a[j], a[j+1]);                  //交换            }        }    }    return;}int main(){    int i;    int N =6;                                                    //数组个数    int s[6] = {5,2,4,6,1,3};         //初始化    for(i = 0;  i < N; i++)        cout<< s[i] <<" ";    cout<<endl;    Insertion_Sort1(s, N);                                     //快速排序    //输出排序后的数组    for(i = 0;  i < N; i++)        cout<< s[i] <<" ";    return 0;}
0 0
原创粉丝点击