插入排序

#include <iostream>
using namespace std;

void insertSort(int a[], int n)
 {
    for (int i = 1; i < n; i++)
    {
        int temp = a[i];
        int j = i - 1;

        for (; j >= 0 && a[j] > temp; j--)
        {
            a[j + 1] = a[j];
        }

        a[j + 1] = temp;
    }

//      for (int i = 1; i < n; i++)
//      {
//          if (a[i] < a[i - 1])
//          {
//              int temp = a[i];
//              int j = i - 1;
//              for (; temp < a[j]; j--)
//              {
//                  a[j + 1] = a[j];
//              }
// 
//              a[j + 1] = temp;
//          }
//      }
 }

int main()
{
    int a[7] = {9,3,2,5,6,4,8};

    int size = sizeof(a)/sizeof(int);

    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

    cout << endl;

    insertSort(a, size);


    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

}

 

posted @ 2013-01-10 03:16  rookieeeeee  阅读(164)  评论(0编辑  收藏  举报