您的位置:首页 > 其它

Recursive version of the insertion sort

2007-02-04 20:49 337 查看
// 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐