Answer to Question #161919 in C++ for Jimmy

Question #161919

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.


1
Expert's answer
2021-02-07T16:49:34-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog