插入排序

来源:互联网 发布:淘宝已付款显示未付款 编辑:程序博客网 时间:2024/05/05 19:54

1.从小到大排列

#include "stdafx.h"void insert_sort(int a[],int len){    int temp,i;    for (int j = 1; j < len ; ++j)    {        temp = a[j];        i = j - 1;        while (i>-1 && a[i] > temp)          //依次比较后,若满足则向前插入        {            a[i + 1] = a[i];            i--;        }        a[i + 1] = temp;    }}int _tmain(int argc, _TCHAR* argv[]){    int a[] = { 3,4,2,6,12,45,5,1 };    insert_sort(a,sizeof(a)/4);    for (int k = 0; k < sizeof(a)/4; k++)    {        cout << a[k] << endl;    }    return 0;}

2.从大到小排列

#include "stdafx.h"void insert_sort(int a[], int len){    int temp, i;    for (int j = len-1; j >-1; --j)    {        temp = a[j];        i = j + 1;        while (i<len+1 && a[i] > temp)                 //从最后一个元素开始比较,若满足则向前移        {            a[i - 1] = a[i];            i++;        }        a[i - 1] = temp;    }}int _tmain(int argc, _TCHAR* argv[]){    int a[] = { 111, 4, 2, 6, 12, 45, 5, 99 };    insert_sort(a, (sizeof(a) / 4)-1);    for (int k = 0; k < sizeof(a) / 4; k++)    {        cout << a[k] << endl;    }    return 0;}

3.从大到小排列

#include "stdafx.h"void insert_sort(int a[], int len){    int temp, i;    for (int j = len-1 ; j > -1; --j)    {        temp = a[j];        i = j + 1;        while (i<len+1 && a[i] > temp)                 //从倒数第二个元素开始比较,若满足则向后移        {            a[i - 1] = a[i];            i++;        }        a[i - 1] = temp;    }}int _tmain(int argc, _TCHAR* argv[]){    int a[] = { 111, 4, 2, 6, 12, 45, 5, 99 };    insert_sort(a, (sizeof(a) / 4) - 1);    for (int k = 0; k < sizeof(a) / 4; k++)    {        cout << a[k] << endl;    }    return 0;}
0 0