write a program in C++ to read an array of stored integers. Search for a value using binary search method. If the element is found, print its location else print element not found
1
Expert's answer
2016-06-23T08:37:03-0400
#include <malloc.h> #include <iostream>
using namespace std;
void bubbleSort(int* arr, int size); int searchBinary(int *arr, int left, int right, int key);
int main() { int *array; // a pointer to an array int i, size; int key = 0;
cout << ("Enter the size of the array: "); cin >> size; // Allocating memory array = (int*)malloc(size * sizeof(int)); // Enter the array elements for (i = 0; i < size; i++) { cout << "[" << i << "] = "; cin >> array[i]; }
bubbleSort(array, size);
// Conclusion sorted array elements cout << "Sorted array:" << endl; for (i = 0; i < size; i++) cout << "[" << i << "] = " << array[i] << endl;
cout << "\nEnter the key: "; cin >> key;
int errorCode = 0; errorCode = searchBinary(array, 0, size, key); if (errorCode != -1) { cout << "The index of the element found: " << errorCode << endl; } else cout << "Element not found!" << endl;
free(array);
system("pause");
return 0; }
void bubbleSort(int* arr, int size) { int tmp, i, j;
for (i = 0; i < size - 1; ++i) // i - passage number { for (j = 0; j < size - 1; ++j) // the inner passage cycle { if (arr[j + 1] < arr[j]) { tmp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = tmp; } } } }
// a binary search algorithm function int searchBinary(int *arr, int left, int right, int key) { int midd = 0; while (1) { midd = (left + right) / 2;
if (key < arr[midd]) // if less than the required value in the cell right = midd - 1; // displace the right search border else if (key > arr[midd]) // if desired more than the value in the cell left = midd + 1; // search displace left border else // otherwise (values are equal) return midd; // the function returns the index of the cell
if (left > right) // if border closed return -1; } }
Comments