sailing

Everything...

Recursive version of the insertion sort

// RecursiveInsertionSort.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <iostream>

using namespace std;

 

void PrintArray(int a[], int iStart, int iEnd);

void InsertionSort(int* a, int length);

 

int _tmain(int argc, _TCHAR* argv[])

{

    // sorted elements start from 1

    int arrayToSort[] = {INT_MIN, 20, 7, 3, 4, 25, 15, 29, 12, 4, 1};

    int n = sizeof(arrayToSort)/sizeof(int);

    PrintArray(arrayToSort, 1, n-1);

    InsertionSort(arrayToSort, n-1);

    PrintArray(arrayToSort, 1, n-1);

    return 0;

}

 

void InsertionSort(int* a, int length)

{

    if(length>1)

    {

        // sort the element before last element

        InsertionSort(a, length-1);

        // insert the last element into the sorted sequence

        int j = length - 1;

        int key = a[length];

        while(j>0 && a[j]>key)

        {

            a[j+1] = a[j];

            j--;

        }

        a[j+1] = key;

    }

}

 

void PrintArray(int a[], int iStart, int iEnd)

{

    for(int i=iStart; i<= iEnd; i++)

    {

       cout<<a[i]<<' ';

    }

    cout<<endl;

}

 

 

posted on 2007-02-04 20:49  乌生鱼汤  阅读(198)  评论(0编辑  收藏  举报

导航