合理吗?
家来看看顺序合理吗?
大#include "stdafx.h"
using namespace System;
//对数组进行二叉搜索
void ShowOutput(int arr[],int low,int mid,int high,int size1)
{
for(int i=0;i<size1;i++){
if(i<low||i>high)
Console::Write(L" ");
else if(i==mid)
Console::Write(L"{0}* ",arr[i].ToString("00"));
else
Console::Write(L"{0} ",arr[i].ToString("00"));
}
Console::WriteLine();
}
int BinarySearch(int arr[],int key,int size2)
{
int low=0,high=size2-1,middle;
while(low<=high){
middle=(low+high)/2;//如结果是偶数,取2个较小的索引值
ShowOutput(arr,low,middle,high,size2);
if(key==arr[middle])
return middle;
else if(key<arr[middle])
high=middle-1;
else
low=middle+1;
}
return -1;
}
int main(array<System::String ^> ^args)
{
int a[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28};
int size3=sizeof(a)/sizeof(int);
Console::Write(L"Please enter a search key:");
int searchKey=Int32::Parse(Console::ReadLine());
Console::WriteLine(L"\nPortions of array searched");
int element=BinarySearch(a,searchKey,size3);
if(element!=-1)
Console::WriteLine(L"\nFound value in element {0}",element.ToString());
else
Console::WriteLine(L"\nValue not found");
return 0;
}//vs2008