插入排序的递归实现和二分查找递归实现,算法导论2.3-4和2.3-5

while语句的时候写成 while(i>=0 && i>key)   没注意,  还纳闷死了,怎么会错。

#include "stdafx.h"
#include <iostream>

using namespace std;

void reInsertSort(int a[], int length);
bool diFind(int a[],int begin,int end,int val);
int main(){
	int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 10 };
	reInsertSort(a, 9);
	for (size_t i=0; i < 10;++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	if (diFind(a, 0, 9, 10)){
		cout << "found" << endl;
	}
	else
	{
		cout << "not found" << endl;
	}
	return 0;
}

bool diFind(int a[], int begin, int end, int val){
	if (begin > end)
	{
		return false;
	}
	int mid = (begin + end) / 2;
	if (a[mid] == val)
	{
		return true;
	}
	else if (a[mid] > val)
	{
		return diFind(a, begin, mid - 1, val);
	}
	else if (a[mid] < val)
	{
		return diFind(a, mid + 1, end, val);
	}
}

void reInsertSort(int a[], int length){
	if (length < 1)
	{
		return;
	}

	reInsertSort(a, length - 1);

	int key = a[length];
	int i = length - 1;
	while (i >= 0 && a[i] > key)
	{
		a[i + 1] = a[i];
		--i;
	}
	a[i + 1] = key;

	
}
    原文作者:查找算法
    原文地址: https://blog.csdn.net/u010116320/article/details/45055017
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞