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;
Related
Hi there i've been tasked with Writing a simple program that is given an array of integers and determines the mode, which is the number that appears most frequently in the array.
The approach i'm trying to adopt is using a bubble sort with a bin search algorithm my level of knowledge is at a beginner stage can someone help point me?
Where i'm going wrong i believe it to be passing the correct search value to find it in the array! But i maybe wrong but some help would be very much appreciated, thanks in advance for those to take time to try help me.
#include <iostream>
using namespace std;
const int arrayLength = 10;
int searchVal;
int numGroup[arrayLength];
bool isSorted(int [], int arrayLength);
int binSearch(int [],int arrayLegth,int searchVal);
int main()
{
// Take in num
for (int index = 0; index < arrayLength; index++)
{
cout << "Enter Number: ";
cin >> numGroup[index];
}
// Sort numbers
//var to hold the val being swaped
int swapHolder = 0;
//bubble sort
for (int iSort = 0; iSort < arrayLength; iSort++)
{
for (int jSort = (iSort + 1); jSort <= arrayLength - 1; jSort++)
{
if (numGroup[iSort] > numGroup[jSort])
{
swapHolder = numGroup[iSort];
numGroup[iSort] = numGroup[jSort];
numGroup[jSort] = swapHolder;
}
}
}
//passes the sorted array and the length to the isSorted
isSorted(numGroup, arrayLength);
return 0;
}
bool isSorted(int numGroup[], int arrayLength){
cout << "Final result" << endl;
for (int index = 0; index < arrayLength - 1 ; index++)
{
if (numGroup[index] > numGroup[index + 1])
{
cout << "it's false";
system("pause");
return false;
}
cout << numGroup[index] << endl;
//cout << arrayLength << endl;
}
cout << numGroup[arrayLength - 1] << endl;
//trying to make searchVal
for (int i = 0; i < numGroup[arrayLength - 1]; i++)
{
if (numGroup[i] == numGroup[i])
{
int searchVal = numGroup[i];
}
}
binSearch(numGroup, arrayLength, searchVal);
cout << "It's true ";
system("pause");
return true;
}
int binSearch(int numGroup[], int arrayLength,int searchVal){
int low = 0;
int high = arrayLength - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
//search through the array
if (searchVal == numGroup[mid])
{
return mid;
}
else if (searchVal > numGroup[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "In bin search " << mid;
return mid;
}
You don't need to sort the array. You can have another array (freq) which will count the numbers appearances. So, a mini code for that:
int myArray[10];
int freq[1000]; //we assume that the numbers are smaller than 1000
void count()
{
for(int i = 0; i < 10; ++i)
{
++freq[v[i]];
}
}
int ReturnModeElement()
{
int maxFreq = -1;
int element = -1;
for(int i = 0 ; i < 10; ++i)
{
if(freq[v[i]] > maxFreq)
{
maxFreq = freq[v[i]];
element = v[i];
}
}
return element;
}
I hope you got the idea :)
Ok, so I was doing a tiny project for school and I can't find the answer anywhere to why this small change in code makes it finish in no time when number m gets higher. Look at the variable "k" I change it from int to long.
I'm trying to find the longest sequence in the Collatz sequence between 1 and 1000000
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
long k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
The question is simple: Why does it run so much faster when input m==1000000?
I see what's happening here. Basically, above certain value for your input, the int is overflowing since you are doing k*3.
I modified your code to check this (see below). Upto input value of around 113000, the max your 'k' has to hold is 1570824735 (close to INT_MAX 2147483647). Anything 114000 or above, 'k' overflows and the code goes into uncharted territory. That problem doesn't happen when you use long of course.
./a.out 113000
j: 1570824735
Lengsta runa: 354
Tala lengstu runu: 106239
#include <iostream>
#include <string>
using namespace std;
void lengstaRuna(int m) {
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
long j = 0;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
if (k*3 > j)
j = k*3;
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "j: " << j << endl;
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
int main (int ac, char** av) {
std::string::size_type sz;
lengstaRuna(std::stoi(av[1]));
}
#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
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
I've been working on this for awhile and I have tried multiple different algorithms for the bubble sort that I have found online but none of them are working properly for me and I'm pretty close to giving up, but this is due tomorrow night. I'd really appreciate if someone could point out where im going wrong. I dont really understand this algorithm with the bool so ill try to find what i was trying before and edit it in
#include <iostream>
using namespace std;
void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);
int main()
{
int size;
int array[500];
GetInfo(array, size);
BubbleSort(array, size);
BinarySearch(array, size);
return 0;
}
void GetInfo(int array[], int& size)
{
cout << "Enter the number of naturals: ";
cin >> size;
cout << "Enter the natural numbers to sort: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
}
void BubbleSort(int array[], int size)
{
int temp;
bool check = true;
int end = 0;
while(check)
{
end++;
check = false;
for(int i = 0; i < size - end; i++)
{
if (array[i] > array[i+1]) //I'm positive this part is correct
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
check = true;
}
}
}
cout << endl << "Numbers sorted in ascending order: " << endl;
for (int i = 0; i < size; i++)
{
cout << array[i] << ' ';
}
}
void BinarySearch(int array[], int size) //this doesnt work properly atm but
{ //should be good when the sort works
int index;
int top = size - 1;
int bottom = 0;
int middle = (top) / 2;
bool found = false;
int target;
cout << endl << "Enter the number to search: ";
cin >> target;
while (found == false)
{
if (target > array[middle])
{
bottom = middle + 1 ;
middle = ((top - bottom)/2) + bottom;
}
else if (target < array[middle])
{
top = middle - 1;
middle = ((top - bottom)/2) + bottom;
}
else
{
found = true;
index = middle;
}
}
cout << "Number " << target << " is found in position " << index << endl;
}
You might meant to swap a[i] with a[i+1] while you actually swapped a[size+1]
These lines are wrong:
array[i] = array[size+1];
array[size+1] = temp;
You need:
array[i] = array[i+1];
array[i+1] = temp;