Добавил:
Studfiles2
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Шпоры по МПиПА / Массивы / Поиск / Двоичный поиск / C / Исходник / binary_Search
.cpp#include "iostream.h"
#include "string.h"
#include "stdio.h"
int binarySearch(int array[], int value, int size)
{
bool found = false;
int high = size - 1, low = 0;
int m = (high + low) / 2;
while ( ( !found ) && ( high >= low ) ){
if ( value == array[m] ){
found = true;
}
else if (value < array[m]){
high = m - 1;
}
else {
low = m + 1;
}
m = (high + low) / 2;
}
if ( found ) return m; else return -1;
}
void easySort( int array[], int length ){
int i, j, item;
for( i = 1; i < length; i++ ){
item = array[i];
j = i;
while ( item < array[j-1] ){
array[j] = array[j-1];
j--;
}
array[j] = item;
}
}
void main(){
int i, size, element;
int *array;
cout << "Binary Search.\nEnter array dimension: ";
cin >> size;
array = new int[size];
cout << "Enter " << size << " elements: ";
for ( i = 0; i < size; i ++ ){
cin >> array[i];
}
easySort( array, size );
cout << "Your array after sorting: ";
for ( i = 0; i < size; i ++ ){
cout << array[i] << " ";
}
cout << "\nEnter element: ";
cin >> element;
cout << "Position of element " << element << " in array is " << binarySearch( array, element, size ) << "\nPress any key to continue..." << endl;
getchar();
}