Write a C++ program to sort a given array of integer numbers and also provide a function
to search for a given element in that sorted array using binary search algorithm.
#include <iostream>
using namespace std;
#define SIZE 7
void arrayPrint(int array[], int size) {
int last = size - 1;
for ( int i = 0; i < last; i++ ) {
cout << array[i] << " ";
}
cout << array[last] << "\n";
}
void arraySort(int array[], int size) {
for ( int i = 0; i < size - 1; i++ ) {
for ( int j = 0; j < size - i - 1; j++ ) {
if ( array[j] >= array[j+1] ) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
int binarySearch(int array[], int number, int min, int max) {
while (min <= max) {
int mid = min + (max - min) / 2;
if (array[mid] == number) {
return mid;
}
if (array[mid] < number) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return -1;
}
int main() {
int array[SIZE] = {3, 2, 4, 1, 7, 5, 6};
int number;
int result;
cout << "Array before sorting is:\n";
arrayPrint(array, SIZE);
cout << "Array after sorting is:\n";
arraySort(array, SIZE);
arrayPrint(array, SIZE);
cout << "\n";
cout << "Enter the number you want to search for in the array: ";
cin >> number;
result = binarySearch(array, number, 0, SIZE);
if ( result != -1 ) {
cout << "This number was found with index " << result << "\n";
} else {
cout << "This number was not found in the array\n";
}
return 0;
}
Comments
Leave a comment