直接插入排序算法

来源:岁月联盟 编辑:猪蛋儿 时间:2011-12-31
#include "stdafx.h" 
#include <iostream> 
using namespace std; 
 
 //直接插入排序算法(升序) 
 void InsertSort(int a[], int n) 
 { 
    int i,j,temp; 
 
    //从第二个元素开始,往前面的已经排序的序列插入,插入n-1次 
    for (i=1; i<n; i++) 
    { 
        //需要插入排序的元素 
        temp = a[i]; 
        for (j=i-1; j>=0 && temp < a[j]; j--) 
        { 
            a[j+1] = a[j]; 
        } 
        a[j+1] = temp; 
    } 
 } 
 
 //输出数组  www.2cto.com
 void Print_Arry(int a[], int n) 
 { 
     for (int i=0; i<n; i++) 
     { 
        cout<< a[i]<<" "; 
     } 
     cout<<endl; 
 } 
 
int _tmain(int argc, _TCHAR* argv[]) 

    int a[9] = {7,3,5,8,9,1,2,4,6}; 
    InsertSort(a, 9); 
    Print_Arry(a, 9); 
    return 0; 


摘自 学无止境

图片内容