Reputation: 13
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.
Upvotes: 0
Views: 168
Reputation: 753675
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.
Upvotes: 1
Reputation: 280485
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
.
Upvotes: 2