Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My program is stuck in an infinite loop, I don\'t know where it is. /** * helper

ID: 3594216 • Letter: M

Question

My program is stuck in an infinite loop, I don't know where it is.

/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for problem set 3
*/

#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
/**
* Return true if value is in array of n values, else false, using linear search.
*/
bool linear_search(int value, int values[], int n)
{
int boolnum = 0;
// Return false if n is negative.
if(n < 1)
return false;
// perform linear search looking for values in values.
for (int i = 0; i < n; i++) {
if (values[i] == value) {
boolnum = 1;
break;
}
}
if (boolnum == 1)
return true;
else
return false;
}
/**
* Returns true if value is in array of n values, else false, using binary search.
*/
bool binary_search(int value, int values[], int n)
{
int start_index = 0;
int end_index = n-1;
while(start_index <= end_index) {
int mid_index = (start_index + end_index) / 2;
if (value == values[mid_index]) {
printf("Got it");
return true;
}
else if (value < values[mid_index]) {
end_index = mid_index + 1;
}
}
return false;
}
/**
* sorts array of n values using selection sort.
*/
void sort(int values[], int n)
{
// find smallest number in unsorted array of size n.
// consider first number as the smallest.
for (int i = 0; i < n; i++) {
int smallest_index = i;
for (int j = i+1; j < n; j++) {
if (values[j] < values[smallest_index])
smallest_index = j;
}
// switch the smallest number with the first number of the unsorted array.
int temp = values[i];
values[i] = values[smallest_index];
values[smallest_index] = temp;
}
return;
}
/**
* Returns true if value is in array of n values, else false.
*/
bool search (int value, int values[], int n)
{
return binary_search(value, values, n);

}

Explanation / Answer

Hi,

The programme is not comming out of infinite loop is because there is some mistake in the function

bool binary_search(int value, int values[], int n)

In this function you have done 2 mistakes

1. Forgotten to add else statement inside the while loop to update the "start_index"

2.The value of end_index should be , end_index = mid_index - 1; instead of mid_index+1

In summary just replace the while loop inside the function "bool binary_search(int value, int values[], int n)"

while(start_index <= end_index) {
int mid_index = (start_index + end_index) / 2;
if (value == values[mid_index]) {
printf("Got it");
return true;
}
else if (value < values[mid_index]) {
end_index = mid_index -1;
}
else
start_index = mid_index +1;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote