i was writing a c++ code for performing binary search in an array,but am unable to wield the desired output. when execute the code, i ma getting a never ending output, what may be the reason behind this?
#include <iostream>
using namespace std;
void Binary(int arr[], int n, int key)
{
int s = 0;
int e = n - 1;
while (s <= e) {
int mid = (s + e) / 2;
if (arr[mid] == key) {
cout << "Element Found At Index No. " << mid;
} else if (arr[mid] > key) {
e = mid - 1;
} else {
s = mid + 1;
}
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "Enter element to be searched!";
cin >> key;
Binary(arr, n, key);
return 0;
}
After you find your element, you generate output but never exit the loop or change either of the values that the loop condition checks.
Simply break out of the loop (or return from the function) after showing your output:
if (arr[mid] == key) {
cout << "Element Found At Index No. " << mid;
break;
}
Answer provided by #1201ProgramAlarm is the right fix. Adding few minor changes:
Instead of using namespace std; it would be better to explicitly provide the scope resolution for std::cin and std::cout
Providing some more print statements while entering the array elements.
#include <iostream>
void Binary(int arr[], int n, int key)
{
int s = 0;
int e = n - 1;
while (s <= e) {
int mid = (s + e) / 2;
if (arr[mid] == key) {
std::cout << "Element Found At Index No. " << mid;
break;
} else if (arr[mid] > key) {
e = mid - 1;
} else {
s = mid + 1;
}
}
}
int main()
{
int n;
std::cout << "Enter Number of elements in the array: ";
std::cin >> n;
int arr[n];
std::cout << "Enter " << n << " sorted array elements: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
int key;
std::cout << "Enter element to be searched!";
std::cin >> key;
Binary(arr, n, key);
return 0;
}
Related
so i am just starting DSA and came across binary search part i had already saw the video tutorial and even articles but couldn't find whats wrong with my code
#include <iostream>
int binarySearch(int arr[], int low,int high, int key)
{
while (low <= high)
{
int mid = (high + low) / 2;
if (arr[mid] == key){
return mid;
} else if (arr[mid] > key){
return low = mid - 1;
} else {
return high = mid + 1;
}
}
return -1;
}
int main()
{
std::cout << "enter the array size: ";
// getting array size
int arrSize;
std::cin >> arrSize;
// intializing array
int arr[arrSize];
// getting array elements
std::cout << "enter array elements: ";
for (int i = 0; i < arrSize; i++)
{
/* code */
int temp;
std::cin >> temp;
arr[i] = temp;
}
// getting key
std::cout << "enter the key to find index: ";
int key;
std::cin >> key;
// getting result
int result = binarySearch(arr,0, arrSize, key);
std::cout << "result: "<<result;
return 0;
}
anyone know where i am getting it worng
output data -
"arrSize: 5"
"arr elements: 10 20 30 40 50"
"key: 50"
"result: 3"
this is your binary search algorithm :
while (low <= high)
{
int mid = (high + low) / 2;
if (arr[mid] == key){
return mid;
} else if (arr[mid] < key){
low = mid + 1;
} else {
high = mid - 1;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
// function for binary search in array
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
e = mid - 1;
else
s = mid + 1;
}
return -1;
}
int main()
{
int n, key;
cout << "enter no. of elements" << endl;
cin >> n;
int arr[n];
cout << "enter array " << endl;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "enter key" << endl;
cin >> key;
cout << binSrch(arr, n, key);
return 0;
}
This code for binary searching in array does not work.
For some array the program gets stuck. I don't know what did wrong.
I entered input in sorted format.
PS C:\Users\anmol\Desktop\c++projectwork> g++ .\binSearchArrFun.cpp
PS C:\Users\anmol\Desktop\c++projectwork> ./a
enter no. of elements
6
enter array
2
3
4
5
6
7
enter key
8
it just stuck here rather than giving -1
Assuming that you are passing n as the size of the array, you should give e = n-1 since arrays are 0-indexed based, that is where you are probably getting the wrong answer.
And you also should calculate mid after each iteration, so it should be inside the while loop.
Also, you should do mid = s +(e-s)/2 to avoid overflow.
I modified your code. Run it and it should become clear what's going on.
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
{
cout << "e = mid - 1;\n";
e = mid - 1;
}
else
{
cout << "e = mid - 1;\n";
s = mid + 1;
}
}
return -1;
}
int main()
{
int n = 4, key = 3;
int arr[100] = { 1,3,4,10 };
cout << binSrch(arr, n, key);
return 0;
}
You can use this modified main for testing. It ouputs test cases that don't work.
int main()
{
int n = 4;
int arr[] = {1,3,4,10,11};
// check for each element of arr if it is found
// at the right position
int index = 0;
for (auto testval : arr)
{
if (! binSrch(arr, n, testval) == index)
cout << "not OK for case" << testval << "\n";
index++;
}
// check if 0 and 100 are not found
if (binSrch(arr, n, 0) != -1)
cout << "not OK for case" << 0 << "\n";
if (binSrch(arr, n, 100) != -1)
cout << "not OK for case" << 100 << "\n";
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm developing a program that reads text files and stores the words in an array that can be sorted and then searched through. I've already tried using a dynamically allocated array to place the words into from the text files, but all I get is string cannot be read error from my getline (this doesn't happen when I use vectors). When I try to print out the vector array to see what is being passed through to my sorting functions, it prints out the memory addresses of the array and not the values stored in the array.
I also get a read access violation in my sorting functions at certain points in the function after I've pass the vector arrays to them and I don't understand why. I do show in the code where the problem is accruing. Please note that I'm very new to coding and this program is far from complete. I'm including all of the code I have done so far because if I just show the problem areas I don't think it will be understandable why I'm having these errors. Any help is appreciated thank you.
#include "flore0900header.h"
int main()
{
string name;
int num = 0, num2 = 0, count = 0;
vector<string> word; //to pass vector array to another function
cout << "Hello. Enter your name: ";
cin >> name;
cout << endl;
cout << "Welcome " << name << " This program lets you test 5 different sorting algorithms using texts files" << endl;
cout << endl;
cout << "Which text file would you like to search?" << endl;
cout << "=========================================" << endl;
cout << "1. The Blue Hotel" << endl;
cout << "2. 20,000 Leagues Under the Sea" << endl;
cout << "3. A Tale of Two Cities" << endl;
cin >> num;
count = text_select(num);
catch_array(&word); //passing vector array by reference. '&' is there because it won't work otherwise
cout << endl;
cout << "Which sorting algorithems would you like to use?" << endl;
cout << "========================================" << endl;
cout << "1. Selection" << endl;
cout << "2. Bubble" << endl;
cout << "3. Insertion" << endl;
cout << "4. Merge" << endl;
cout << "5. Quick" << endl;
cin >> num; cin >> num2;
sort_select(num, &word, count);//'&' is there because it won't work otherwise
sort_select(num2, &word, count);//'&' is there because it won't work otherwise
cout << endl;
cout << "Ok! Running algorithms..........." << endl;
}
the header file
#ifndef FLORE0900HEADER_H
#define FLORE0900HEADER_H
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <istream>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <ostream>
/* some of the includes are not needed, I haven't removed the un-needed ones yet*/
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
void selection_sort(vector<string> a[], int size);
void bubble_sort(vector<string> a[], int size);
void insertion_sort(vector<string> a[], int size);
void merge_sort(vector<string> a[], int from, int to);
void quick_sort(vector<string> a[], int from, int to);
int text_select(int num);
void sort_select(int num, vector<string> a[], int size);
vector<string> catch_array(vector<string> a[]);
void merge(vector<string> a[], int from, int mid, int to);
int min_position(vector<string> a[], int from, int to);
int partition(vector<string> a[], int from, int to);
void swap(int& x, int& y);
void print(vector<string> a[], int size);
#endif
text_select function file
#include "flore0900header.h"
//#include <vector>
int text_select(int num)
{
int count = 0;
vector<string> words(100000);
//vector<string>* word2 = new vector<string>[count];
std::ifstream infile;
if (num == 1)
{
infile.open("blue_hotel.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);//string read error when using not using vector
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 2)
{
infile.open("2under.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 3)
{
infile.open("2city10.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else
cout << "not a valid choice try again" << endl;
infile.close();
catch_array(&words);//if I don't use '&' the vector won't pass through
return count;
}
vector<string> catch_array(vector<string> a[])
{
return *a;//if I don't put '*' before the 'a' I get an error
}
sort_select file
#include "flore0900header.h"
void sort_select(int num, vector<string> a[], int size)
{
int from = 0;
if (num == 1)
{
selection_sort(a, size);
}
else if (num == 2)
{
bubble_sort(a, size);
}
else if (num == 3)
{
insertion_sort(a, size);
}
else if (num == 4)
{
merge_sort(a, from, size);
}
else if (num == 5)
{
quick_sort(a, from, size);
}
else
cout << "not a valid pick try again" << endl;
}
selection_sort file
#include "flore0900header.h"
void selection_sort(vector<string> a[], int size)
{
int next;
for (next = 0; next < size - 1; next++)
{
print(a, size);//to see what is being passed to the function
int min_pos = min_position(a, next, size - 1);
swap(a[next], a[min_pos]);
}
}
int min_position(vector<string> a[], int from, int to)
{
int min_pos = from;
for (int i = from + 1; i <= to; i++)
{
if (a[i] < a[min_pos])//read access violation happens here
{
min_pos = i;
}
}
return min_pos;
}
void print(vector<string> a[], int size)
{
for (int i = 0; i < size; i++)
{
cout << &a[i] << " ";//is printing memory locations instead of values
}
cout << endl;
}
bubble_sort file
#include "flore0900header.h"
void bubble_sort(vector<string> a[], int size)
{
for (int i = 0; i < size - 1; i++) //loop for recording no# of iteration needed to complete the sorting
{
int flagForSwap = 0; //creates a flag variable that accounts for wheather the swap function is called at all
//loop for counting comparisons
for (int j = 0; j < size - 1 - i; j++)
{
if (a[j] > a[j + 1]) //(read access violation happens here) compare adjacent array elements
{
swap(a[j], a[j + 1]); //completes the swap
flagForSwap = 1; // flag to 1 if swap is used
}
}
if (flagForSwap == 0) //breaks the iteration loop if inputed array is already sorted and no swap is needed
{
break;
}
}
}
void swap(int& x, int& y)
{
int temp = x; //creates a temp variable to store the value of the current element
x = y; // change the value of the current element to next element
y = temp; //assigns the value of temp to next element
}
insertion_sort file
#include "flore0900header.h"
void insertion_sort(vector<string> a[], int size)
{
for (int i = 1; i < size; i++)
{
vector<string> next = a[i];//read access violation happens here
int j = i;
while (j > 0 && a[j - 1] > next)
{
a[j] = a[j - 1];
j--;
}
a[j] = next;
}
}
merge_sort file
#include "flore0900header.h"
void merge_sort(vector<string> a[], int from, int to)
{
if (from == to)
{
return;
}
int mid = (from + to) / 2;
merge_sort(a, from, mid);
merge_sort(a, mid + 1, to);
merge(a, from, mid, to);
}
void merge(vector<string> a[], int from, int mid, int to)
{
int n = to - from + 1;
vector<string>* b = new vector<string>[n];
int i1 = from;
int i2 = mid + 1;
int j = 0;
while (i1 <= mid && i2 <= to)
{
if (a[i1] < a[i2])//read access violation happens here
{
b[j] = a[i1];
i1++;
}
else
{
b[j] = a[i2];
i2++;
}
j++;
}
while (i1 <= mid)
{
b[j] = a[i1];
i1++;
j++;
}
while (i2 <= to)
{
b[j] = a[i2];
i2++;
j++;
}
for (j = 0; j < n; j++)
{
a[from + j] = b[j];
}
delete[] b;
}
quick_sort file
#include "flore0900header.h"
void quick_sort(vector<string> a[], int from, int to)
{
if (from >= to)
{
return;
}
int p = partition(a, from, to);
quick_sort(a, from, p);
quick_sort(a, p + 1, to);
}
int partition(vector<string> a[], int from, int to)
{
vector<string> pivot = a[from];
int i = from - 1;
int j = to + 1;
while (i < j)
{
i++;
while (a[i] < pivot)//read access violation happens here
{
i++;
}
j--;
while (a[j] > pivot)
{
j--;
}
if (i < j)
{
swap(a[i], a[j]);
}
}
return j;
}
There is no such thing as "a vector array".
You can have arrays of vectors, but you don't.
Yet, here, your function is written as if it does:
int partition(vector<string> a[], int from, int to)
// ^^
I imagine this was done because, before you added the [] here and the & there, your functions appeared not to do anything.
That was because you were passing the vector by value, so changes in the function were made to a copy, and thus not reflected in the calling scope.
Your changes allowed the code to compile, and possibly even "work" in some obscure cases, but only by chance; the [INDEX] syntax is shared between vectors and arrays. But you don't have an array, so pretending to the function that you do is wrong. Most of your accesses go out of bounds.
Also note that if you didn't have a bool operator<(const vector<string>&, const vector<string>&) defined somewhere, it wouldn't compile.
Anyway, the solution to use your one vector is simple:
Get rid of that []
Get rid of that &
Change what is now vector<string> into vector<string>&. That & means "take a reference".
#include <iostream>
using namespace std;
const int lab8 = 10;
int labArray[lab8];
void promptUser(int [], int);
void sortArray(int [], int);
void showArray(const int[], int);
int searchArray(const int [], int, int value);
int x = 0;
int results = 0;
int main()
{
promptUser(labArray, lab8);
sortArray(labArray, lab8);
showArray(labArray, lab8);
cout << "Choose an integer you want to search from the array: " << endl;
cin >> x;
results = searchArray(labArray, lab8, x);
if (results == -1) {
cout << "That number does not exist in the array. \n";
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
}
void promptUser(int numbers[], int size)
{
int index;
for (index = 0; index <= size - 1;index++ )
{
cout << "Please enter ten numbers to fill the array " << endl
<< (index + 1) << ": ";
cin >> numbers[index];
}
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << "The array you entered when sorted was: ";
cout << array[count] << " ";
cout << endl;
}
}
int searchArray(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = - 1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
I am new to c++ and just working on an assignment for my class. I thought the program I wrote would have worked but for the life of me I can not figure out why it will not compile. I am sure I am missing something or not understanding how it should work completely. The errors I keep receiving are expected expression on line 26 by the 'else' statement and when I put the 'if' and 'else' statements in I started receiving function not allowed here errors. Any help would be greatly appreciated.
In the if statement, you open the bracket { but you never close it. Not sure if this is the problem but it should raise some issues.
if (results == -1) {
cout << "That number does not exist in the array. \n";
**}**
else
{
cout << "The integer you searched for was for at element " << results;
cout << " in the array. \n";
}
This is how it should look. Try it
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Im having a problem with a binary search function. It only seems to work when the randomly generated search key is already in the middle position of the array. Ive tried a lot of things but cant seem to figure out why it's doing this.
#include<iostream>
#include<ctime>
using namespace std;
void printarray(int[], int);
void fillarray(int[], int);
void descendingSort(int[], int);
int binarySearch(int[], int, int);
int main()
{
srand((unsigned int)time(0));
bool quit = false;
while (quit == false)
{
int key = rand() % 100 + 1;
const int size = 16;
int mainarray[size] = {};
fillarray(mainarray, size);
printarray(mainarray, size);
descendingSort(mainarray, size);
cout << endl;
cout << "Ordered array after selection sort:" << endl;
printarray(mainarray, size);
cout << endl;
int result = binarySearch(mainarray, size, key);
cout << "Searching for key value " << key << endl;
if (result >= 0)
{
cout << "Key value " << key << " found at position " << result << endl;
}
else
{
cout << "Key value " << key << " not found!" << endl;
}
cout << "Continue (y/n)? :";
char x;
cin >> x;
cout << endl;
if (x == 'y')
quit = false;
if (x == 'n')
quit = true;
}
return 0;
}
void printarray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
}
void fillarray(int random[], int size)
{
for (int j = 0; j <= size - 1; j++)
{
random[j] = rand() % 100 + 1;
}
}
void descendingSort(int array[], int size)
{
int max, next;
for (int i = 0; i < size - 1; i++)
{
max = i;
for (int j = i + 1; j < size; j++)
{
if (array[max] < array[j])
max = j;
}
if (max!= i)
{
next = array[i];
array[i] = array[max];
array[max] = next;
}
}
}
int binarySearch(int array[], int size, int key)
{
int low = 0, high = size - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (key == array[mid])
{
return mid;
}
else if (key < array[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1;
}
Since you are sorting in descending order, your case is backwards.
See code below where I replaces > with <
if (key == array[mid])
{
return mid;
}
else if (key > array[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
By adding some code above the if it allowed me to visualize what was going wrong.
cout << "Searching in: ";
for (int i = low; i < high + 1; i++)
{
cout << array[i] << " ";
}
cout << endl;