直接插入排序的实现(递归和非递归)

来源:互联网 发布:selina烧伤事件 知乎 编辑:程序博客网 时间:2024/06/06 07:56
// 递归和非递归实现直接插入排序.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;//插入排序(非递归)void InsertSort(int *pArr, int nLength){if (pArr == NULL || nLength <= 0){return;} int key = 0;int j=0;for (int i=1; i<nLength; i++){if (pArr[i] < pArr[i-1])//当前带插入的元素比有序序列的最后一个元素小{   key = pArr[i];           for (j=i-1; j>=0&&key<pArr[j]; j--)           {   pArr[j+1] = pArr[j];             }   pArr[j+1] = key;}}}//插入排序(递归)void InsertSortRecursively(int *pArr, int index, int nLength){if (index >= nLength){return;}int key = pArr[index];//记录当前待插入的元素int i=0;for (i=index-1; i>=0&&key<pArr[i]; i--){pArr[i+1] = pArr[i];}pArr[i+1] = key;InsertSortRecursively(pArr, index+1, nLength);}int _tmain(int argc, _TCHAR* argv[]){int nArr[9] = {8,0,4,7,4,3,8,5,0};InsertSort(nArr, 9);//InsertSortRecursively(nArr, 1, 9);for (int i=0; i<9; i++){cout << nArr[i] << " ";}cout << endl;system("pause");return 0;}