In: Computer Science
I would like to integrate a bubble sort into this binary search
in c ++ Thank you!
#include <iostream>
using namespace std;
// Binary search algorith
// f is the first , l is the last , t is the target
int binarySearch(int stgrade[], int f, int l, int t)
{
while (f <= l)
{
int m = f
+ (l - l) / 2;
// Check if x is present at mid
if
(stgrade[m] == t)
return m;
// If x greater, ignore left half
if
(stgrade[m] < t)
f = m + 1;
// If x is smaller, ignore right half
else
l = m - 1;
}
// if we reach here, then
element was not present
return -1;
}
int main(void)
{
int target;
int stgrade[] = { 100, 73, 94, 100, 70, 86, 55,
90, 74 };
// size of the array
int s = sizeof(stgrade) /
sizeof(stgrade[0]);
cout << "This is your list" <<
endl;
for (int i = 0; i < s; i++)
cout << stgrade[i]
<< " ";
cout << endl;
cout << "Input the target to find , in or
out side of your list" << endl;
cin >> target;
// 0 is the index of 1st element
// s is the size and s-1 is in dext of last
element
// target is what you want to find
int result = binarySearch(stgrade, 0, s - 1 ,
target);
if (result == -1)
cout << "Your target
NOT FOUND in the list" << endl;
else
cout << "Your target is
in the list " << result + 1 << endl;
system("pause");
return 0;
}
#include <iostream> using namespace std; // Binary search algorith // f is the first , l is the last , t is the target int binarySearch(int stgrade[], int f, int l, int t) { while (f <= l) { int m = f + (l - l) / 2; // Check if x is present at mid if (stgrade[m] == t) return m; // If x greater, ignore left half if (stgrade[m] < t) f = m + 1; // If x is smaller, ignore right half else l = m - 1; } // if we reach here, then element was not present return -1; } // Bubble sort algorithm // size is the size of the array void bubbleSort(int stgrade[], int size) { int temp; for (int i = 0; i < size; ++i) { for (int j = 0; j < size - 1; ++j) { if (stgrade[j] > stgrade[j+1]) { temp = stgrade[j]; stgrade[j] = stgrade[j + 1]; stgrade[j + 1] = temp; } } } } int main(void) { int target; int stgrade[] = {100, 73, 94, 100, 70, 86, 55, 90, 74}; // size of the array int s = sizeof(stgrade) / sizeof(stgrade[0]); bubbleSort(stgrade, s); // sort the array cout << "This is your list" << endl; for (int i = 0; i < s; i++) cout << stgrade[i] << " "; cout << endl; cout << "Input the target to find , in or out side of your list" << endl; cin >> target; // 0 is the index of 1st element // s is the size and s-1 is in next of last element // target is what you want to find int result = binarySearch(stgrade, 0, s - 1, target); if (result == -1) cout << "Your target NOT FOUND in the list" << endl; else cout << "Your target is in the list " << result + 1 << endl; system("pause"); return 0; }