I have a code that searches for a given entry in an array, and returns the position in the array of that entry, provided one knows the array contain that number. However, a strange thing happens. When I try to test the code with some concrete arrays, the code works well for some entries, and it does not work for others. The code is this:
#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
int a = (n/2);
int b = n;
int tmp = 0;
while (x != data[a])
{
if (x > data[a])
{
tmp = a;
a = (b+a)/2;
b = b;
}
if (x < data[a])
{
a = tmp;
b = a;
}
}
return a;
}
(in a previous version I was using the floor function to round the numbers contained in a to their integer parts, but I understand this is not necessary.)
I have tested the program for example for the following array in this main:
int main()
{
int n = 6; int x = 12;
int array1[] = {3,12,5,9,7,11};
cout << "The entry " << x << " is found at position "
<< 1+Find_entry(array1, n, x) << endl;
return 0;
}
When I type as in this example x=12, the program gives the correct answer 1. Same thing for x=3, x=11 and x=9. But if I type x=7 or x=5, the program refuses to give an output and I get a message like
"Process terminated with status -1073741510 (0 minute(s), 9 second(s))".
Can anybody explain what's the problem here? How can be the code fixed?? Thank you all for your answers.
You cannot use binary search for unsorted array. Use linear search.
int Find_entry(int data[], int n, int x)
{
int a = 0;
while (a < n && x != data[a]) a++;
return a;
}
Binary search only works on sorted inputs.
Related
I am a newbie. I wanted to make a binary search function in C++ that didn't take the upper and lower bounds of the array as an arguments. For me, I know the array will be of size 10 no matter what therefore I put r = 9. This code works and took me a while to figure out.
I made this post to ask if there are any better ways to go about this without introducing any new header files. I suspect some of the stuff I did in this code were unnecessary. Can you guys tell me any better ways to write this same function?
#include <iostream>
using namespace std;
void binarySearch(int arr[], int n){
bool check = false;
int l = 0;
int r = 9;
while (r - l > 0){
int c;
int m = (r - l) / 2;
if (m!=0) m+=l;
if (m==0 && c==m) m=l+1;
if (arr[m]==n){
cout << "Present. \nPostion: " << m+1;
check = true;
break;
}
else if (arr[m]<n && m!=0) l = m;
else if (arr[m]>n && m!=0) r = m;
c = m;
}
if(!check){
cout << "Absent.";
}
}
int main()
{
int arr[10] = {5,15,25,35,45,55,65,75,85,95};
int n = 95;
binarySearch(arr,n);
return 0;
}
really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Selection Sort :
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
return m;
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void selectionSort(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); ++i)
{
int min = findMin(arr, i);
swap(arr[i], arr[min]); // Assume a correct swap function
}
}
}
void print(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "";
cout << endl;
}
}
}
int main()
{
vector<int> sort;
sort.push_back(2);
sort.push_back(1);
sort.push_back(7);
sort.push_back(4);
sort.push_back(5);
sort.push_back(3);
print(sort);
cout << "this was unsorted array";
cout << endl;
cout << findMin(sort, 0);
cout << "this was minimum";
cout << endl;
selectionSort(sort);
print(sort);
}
I am getting the following results:
comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
}
^
1 warning generated.
2
1
7
4
5
3
this was unsorted array
1
this was minimum
1
2
4
5
3
0
My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"?
Thanks in advance! Sorry for the noob question.
I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well.
You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element.
And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value.
It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop:
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
}
return m;
}
There is a task. It is necessary in a one-dimensional array of N real numbers to calculate the number of the maximum modulo element among unpaired numbers.
I wrote the code, but it does not work. I can’t understand what’s wrong with him.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
setlocale(0, "");
const int KolEl = 5;
int mas[KolEl];
int max = abs(mas[0]);
int result;
for (int i = 0; i < KolEl; i++)
{
cout << " Введите елемент[" << i << "] = ";
cin >> mas[i];
if (mas[i] % 2 == 1) {
if (abs(mas[i]) > max) {
result = i;
cout << result << endl;
}
}
}
system("pause");
}
You initialize max as:
int mas[KolEl];
int max = abs(mas[0]);
However, the values in mas[] are garbage values (read: undefined behavior). So now the value in max is also UB.
You then go on to use that value to compare to the input you take:
if (abs(mas[i]) > max) {
So the result of that comparison is undefined.
You probably meant to declare max as something like:
int max = INT_MIN;
So that the first comparison will always be true (every int except INT_MIN will be greater than it).
I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);
Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].
So, ultimately, your code should look like this:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:
start++;
return recursiveMinimum(searchVector, start, end);
The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.
As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )
I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:
Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a
variable result at 0 and add x to it x times). Then run some version of “the first program” using that square().
Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:
int square(int x)
{
int i = 0;
for(int counter = 0; counter < x; ++counter)
{
i = i + x;
}
return i;
}
But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?
Mats Petersson stole the idea out of my head even before I thought to think it.
#include <iostream>
template <typename T>
T square(T x) {
if(x < 0) x = T(0)-x;
T sum{0}, s{x};
while(s) {
if(s & 1) sum += x;
x <<= 1;
s >>= 1;
}
return sum;
}
int main() {
auto sq = square(80);
std::cout << sq << "\n";
}
int square(int x) {
int result = { 0 };
int *ptr = &result;
for (int i = 0; i < x; i++) {
*ptr = *ptr + x;
}
return *ptr;
}
I am reading that book atm. Here is my solution.
int square(int x)
{
int result = 0;
for (int counter = 0; counter < x; ++counter) result += x;
return result;
}
int square(int n)
{
// handle negative input
if (n<0) n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i=1; i<n; i++)
res += n;
return res;
}
//Josef.L
//Without using multiplication operators.
int square (int a){
int b = 0; int c =0;
//I don't need to input value for a, because as a function it already did it for me.
/*while(b != a){
b ++;
c = c + a;}*/
for(int b = 0; b != a; b++){ //reduce the workload.
c = c +a;
//Interesting, for every time b is not equal to a, it will add one to its value:
//In the same time, when it add one new c = old c + input value will repeat again.
//Hence when be is equal to a, c which intially is 0 already add to a for a time.
//Therefore, it is same thing as saying a * a.
}
return c;
}
int main(void){
int a;
cin >>a;
cout <<"Square of: "<<a<< " is "<<square(a)<<endl;
return 0;
}
//intricate.
In term of the running time complexity,your implementation is clear and simply enough,its running time is T(n)=Θ(n) for input n elements.Of course you also can use Divide-and-Conquer method,assuming split n elements to n/2:n/2,and finally recursive compute it then sum up two parts,that running time will be like
T(n)=2T(n/2)+Θ(n)=Θ(nlgn),we can find its running time complexity become worse than your implementation.
You can include <math.h> or <cmath> and use its sqrt() function:
#include <iostream>
#include <math.h>
int square(int);
int main()
{
int no;
std::cin >> no;
std::cout << square(no);
return 0;
}
int square(int no)
{
return pow(no, 2);
}