我写过如下的二进制搜索。当我试图找到10时,它没有向我显示结果。我错过了什么?
// BinarySearch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void BinarySearch(int arr[],int value);
int * insertionshot(int arr[]);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int value;
cin >> value ;
static int *ptr;// = new int[10];
ptr = insertionshot(arr);
BinarySearch(ptr,value);
return 0;
}
int * insertionshot(int arr[])
{
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = arr[i];
}
int arrlength = sizeof(ar)/sizeof(ar[0]);
for(int a = 1; a <= arrlength -1 ;a++)
{
int b = a;
while(b > 0 && ar[b] < ar[b-1])
{
int temp;
temp = ar[b-1];
ar[b-1] = ar[b];
ar[b] = temp;
b--;
}
}
return ar;
}
void BinarySearch( int a[],int value)
{
int min,max,middle;
min = 0;
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = a[i];
}
//printf("size of array = %d",sizeof(arr));
max = (sizeof(ar)/sizeof(ar[0]) -1);
middle = (min+max)/2;
while(min <= max)
{
if(ar[middle] == value)
{
cout << "The value found" << ar[middle];
break;
}
else if(ar[middle] < value)
{
min = middle +1;
}
else if(ar[middle] > value)
{
max = middle-1;
}
middle = (min+max)/2;
}
}
最后我让它成功了,我认为这段代码没有任何问题。这可以帮助任何人
// BinarySearch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void BinarySearch(int arr[],int value);
int * insertionshot(int arr[],int);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int * arr1 = new int[10];
for(int i = 0;i< sizeof(arr)/sizeof(arr[0]);i++)
{
arr1[i] = arr[i];
}
int value;
cin >> value ;
int *ptr = new int[10];
ptr = insertionshot(arr1,10); // address of sorted array will be returned.
BinarySearch(ptr,value);
arr1 = 0;
ptr =0;
delete arr1;
delete ptr;
return 0;
}
int * insertionshot(int arr1[],int n)
{
for(int a = 1; a <= n -1 ;a++)
{
int b = a;
while(b > 0 && arr1[b] < arr1[b-1])
{
int temp;
temp = arr1[b-1];
arr1[b-1] = arr1[b];
arr1[b] = temp;
b--;
}
}
return arr1;
}
void BinarySearch( int a[],int value)
{
int min,max,middle;
min = 0;
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = a[i];
}
max = (sizeof(ar)/sizeof(ar[0]) -1);
middle = (min+max)/2;
while(min <= max)
{
if(ar[middle] == value)
{
cout << "The value found" << ar[middle];
break;
}
else if(ar[middle] < value)
{
min = middle +1;
}
else if(ar[middle] > value)
{
max = middle-1;
}
middle = (min+max)/2;
}
}