why is bubble sort not working [closed] - c++

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 6 years ago.
Improve this question
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}

You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...

Related

I can't solve this C++ exercise [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I either get a infinity loop, 0, or 9. The question reads as follows:
Create a for loop that compares the two strings starting from index 0. For each match, add one point to user score Upon a mismatch, exit the loop using a break statement.
int main() {
string simonPattern;
string userPattern;
int userScore = 0;
int i = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
/* Your solution goes here */
cout << "userScore: " << userScore << endl;
return 0;
}
Some of my tries:
for ( i = 0; simonPattern <= userPattern; ++i ) {
while( simonPattern.at(0) == userPattern.at(0) ) {
++userScore;
if( simonPattern.at(0) != userPattern.at(0) ){
break;
}
}
while ( simonPattern.at(1) == userPattern.at(1) ) {
++userScore;
if( simonPattern.at(1) != userPattern.at(1) ){
break;
}
So until 9.
Another one:
for (int i=0;i < simonPattern.length(); ++i) {
userScore = i ; }
Can't understand what you tried to do in your first approach.
Will modify your second approach here a bit, by adding comparision in the loop body for when to increment score and when to exit from loop, and also changing the loop termination condition a bit.
Approach
We are using the variable userScore to keep track of score of user. Also storing length of the two strings in variables simonPatternLength and userPatternLength to keep track of when one ends.
For the indices of the strings starting from 0, till one of them ends do the following -
1. If current index is equal in both increase userScore by 1
2. else upon mismatch break out of loop
Code
int main() {
string simonPattern;
string userPattern;
int userScore = 0;
int i = 0;
userScore = 0;
simonPattern = "RRGBRYYBGY";
userPattern = "RRGBBRYBGY";
/* Your solution goes here */
int simonPatternLength = simonPattern.size();
int userPatternLength = userPattern.size();
for(i = 0; i < simonPatternLength && i < userPatternLength; ++i){
if(simonPattern[i] == userPattern[i]){
userScore++;
}
else{
break;
}
}
cout << "userScore: " << userScore << endl;
return 0;
}

(c++) Cannot get void functions to work, having trouble with a few lines inside of the main.cpp as well [closed]

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 5 years ago.
Improve this question
I'm having some trouble with the code that I've put below. The void functions seem to be fine, but they aren't working. I'm not sure what I've done wrong, so any help is appreciated. Also, I don't know how to use an if statement to call in questions from an infile for two players, as shown below this. Please, I have to turn it in at 11pm 12/3 and any help is appreciated. I've already been working on it for 5 hours now
if statement here to display odd number of questions to player1 and even number of questions to player2, make sure to add the correct score for respective player by calling the function upDateScoreDouble
void getHistory (playerHistory pHist[], int loopy, ifstream& inQuest)
{
int i = 0 ;
loopy = 22 ;
while( i < loopy, i++)
{
inQuest >> pHist[i].alias1 ;
inQuest >> pHist[i].score ;
inQuest >> pHist[i].difficulty ;
inQuest >> pHist[i].date ;
}
return ;
}
void bubblesort (playerHistory pHist[], int length)
{
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < length - j; i++) {
if (pHist[i].score > pHist[i + 1].score) {
tmp = pHist[i].score;
pHist[i].score = pHist[i + 1].score;
pHist[i + 1].score = tmp;
swapped = true;
}
}
}
return ;
}
///3.3.6 create a loop to call the getQuestion function for each question
for(int loopy=1; loopy<=numQuestions; loopy++)
{
///3.3.6.2 getQuestion function call
getQuestion(gameQ, numQuestions, inQuest) ;
///3.3.6.1 if statement here to display odd number of questions to player1 and even number of questions to player2
///make sure to add the correct score for respective player by calling the function upDateScoreDouble
if(loopy < numQuestions)
{
inQuest >> gameQ[loopy].question;
cout << gameQ[loopy].question ;
cout << gameQ[loopy].answer ;
cout << gameQ[loopy].ans1 ;
cout << gameQ[loopy].ans2 ;
cout << gameQ[loopy].ans3 ;
cout << gameQ[loopy].ans4 ;
}
} ///end of for loop of number of questions
In the getHistory function it looks like you want a for loop instead.
Because the expression i < loopy, i++ evaluates i < loopy and then throws away the result.
Instead the condition of the loop is i++, and since it's 0 in the first iteration the result is false and the loop never happens.
Read more about the comma-operator in e.g. this reference.
You probably want something like
for (int i = 0; i < 22; ++i) { ... }

Wrong value output [closed]

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 5 years ago.
Improve this question
I'm trying to make the program give me the lowest and the highest value in the array.
Here's my code :
int z=10;
int a[z]={1,2,3,4,5,6,7,8,9,10};
for (int x=1;x<=10;x++) {
cout << "How many pancakes were eaten by P"<<x<<endl;
cin >> a[x];}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x <= z; x++) {
if (a[x] >= maxPancakes) {
maxPancakes = a[x];
glutton = x;
}
else if (a[x] <= minPancakes) {
minPancakes = a[x];
mN = x;
}
}
The code for the highest value is working, but the code for the lowest value keeps on giving me wrong values (random big numbers)
i'd appreciate any help,thank you.
First of all use standard library. It will make your life easier and code safer (and most of the time also faster).
For the array since C++11 you can use std::array, if you are working with the older C++ standard you can use std::vector.
Please note that in your code you are creating array with 10 elements but in the second loop you are iterating 11 times. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and... 10.
The value of the a[10] is undefined, it can be anything (random value).
In the first for loop you are setting the values for a[1] (second element), a[2] (third element), ... , a[10] (eleventh element, bad!).
Fix this loops and check what will happen. You can also start "debugging" with something easier than gdb (which is awesome btw. and you should learn it). You can simply print the values (read about std::cout) in every iteration to see when exactly this "random big numbers" are found.
EDIT
for (int x = 0; x < 10; x++)
{
cout << "How many pancakes were eaten by P" << x << endl;
cin >> a[x];
}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x < z; x++)
{
if (a[x] > maxPancakes)
{
maxPancakes = a[x];
glutton = x;
}
else if (a[x] < minPancakes)
{
minPancakes = a[x];
mN = x;
}
}

How do i implement bubblesort and where [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The task is to implement a bubblesort function followed by a linearsearch aka "linsok" in my "familj" array. the array keeps both the name and the age, so i want to sort the array after their age and print it out. ive got the line search to work but now im stuck with the bubblesort.
The problem is that i dont know how to make my bubble sort code work for this code.
so do i implement the second piece of code in this?
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string namn;
int alder;
void skrivUt(string _namn, int _alder)
{
namn = _namn;
alder = _alder;
}
};
int linsok(Person* PersonArray, int key)
{
for (int i = 0; i < 4; i++)
{
if (PersonArray[i].alder == key)
return i;
}
return -1;
}
int main()
{
Person familj[4];
familj[1].skrivUt("Emma",23);
familj[3].skrivUt("Emilia",29);
familj[2].skrivUt("Johan",26);
familj[0].skrivUt("Timmy ",21);
int index = linsok(familj,22); //the age of the person im looking for.
if(index== -1)
cout << "Personen hittades ej!"; //person not found
else
//prints out the persons name and the index.
cout << "Personen heter " << familj[index].namn << " hen finns på index " << index << endl;
cin.get();
return 0;
}
This is the piece of bubble-sort code i used before and it works.
int p [] = {10,56,73,23,31,24,43};
int a = 6;
for (int i = 0; i < a; i++)
{
int nrLeft = a - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j] > p[j+1])
{
int temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
for(int i = 0; i < 7; i++)
cout << p[i] << endl;
cin.get();
It's likely that you want to convert this to a function that you pass your array of Person objects to, along with the size of it, and then you just access the part that you want to compare. Since you'd be implementing it as a function, you can use it in the same way you use your linsok function, although you'd probably want it to return the sorted array as opposed to an index.
Disclaimer for following code: Neither run nor compiled
Person* bubbleSort(Person* p, int size)
{
for (int i = 0; i < size; i++)
{
int nrLeft = size - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j].alder > p[j+1].alder)
{
Person temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
return p;
}
That's based off you sorting them by alder (which I guess is age? I don't speak Swedish(?)) You just need to provide the signature, and alter it based on your needs, but the basic idea is that you just change what you compare, and the data types.
Another way to do this is to return an int or void(But you should return an int to tell you if it was successful or not), and pass a pointer to the array, so Person** in the signature, and operate directly on that array, but that's a little more difficult, and arguably bad practice, depending on use case.

Bubble Sort program does not output result

I am in a discrete mathematics class and one of the hw problems is to implement a bubble sort. Here's my futile attempt because it does not output the solution. Please advice. Thank you.
#include <iostream>
#include <cstdlib>
using namespace std;
void BubbleSort();
int array1[100] = {0};
int k;
int main()
{
cout << "Enter your numbers and when you are done, enter 0000:\n";
int x = 0;
int i;
while (i != 0000)
{
cin >> i;
array1[x] = i;
x++;
k = x;
}
BubbleSort();
system("pause");
return 0;
}
void BubbleSort(){
int temp;
for( int i = 0; i < k; i++ ){
if ( array1[i] > array1[i+1]){
temp = array1[i+1];
array1[i+1] = array1[i];
array1[i] = temp;
}
}
int x = 0;
while (x <= k)
{
cout << array1[x] << "\n";
x++;
}
}
Please only use basic programming techniques because this is my first programming class. Thank you.
Edit: fixed the relational operator. But now I get incorrect results.
while (x >! k)
This doesn't do what you think it does. If you want something that says "while x is not greater than k", you want <=. Since array1[k] isn't one of the elements you sorted, though, you probably want <.
while (x < k)
Note that for exists for loops like these:
for (int x = 0; x < k; x++) {
cout << array1[x] << "\n";
}
As for the new bug, you're only doing one round of bubbling in your bubble sort. You need another for loop. Also, i is never initialized in main, and i != 0000 isn't going to check whether the user literally entered 4 zeros. It'll only check whether the user's input was equal to the number 0.
The primary problem is here:
while (x >! k)
On the first iteration, the condition checks whether (0 > !k), and k is not 0, so !k is 0, so the condition is false and the loop never executes. Try using:
for (int x = 0; x < k; x++)
cout << array1[x] << "\n";
You also have a problem in the sort phase of your bubble sort; you only iterate through the data once, which is not enough to sort it, in general.
Finally, some design issues.
You should have one function to sort the data and a separate function to print it. Don't combine the two functions as you have done here.
Avoid global variables. Pass the array and its operational length to the sort function, and to the print function if you have one.