I'm trying to code a bubble sort. I'm unable to find the error, I think it has to do with swapping. Can someone tell me where the bug is? It's throwing some unwanted elements at the end of the array.
#include <iostream>
#include <windows.h>
using namespace std;
void swap(int* a,int* b) {
int *c;
c = a;
a = b;
b = c;
return;
}
int main()
{
int array[4], a = 0;
cout << "Enter 5 numbers to be bubble sorted" << endl;
for (a = 0; a <= 4; a++)
{
std::cin >>array[a];
Sleep(1000);
}
for (int b = 0; b <= 4; b++)
{
for(int f = 4;f >= b; f--)
{
if (array[f] < array[f-1])
{
swap(array[f],array[f-1]);
}
}
}
for(int d = 0; d <= 4; d++)
{
cout << '\n';
cout << array[d] << '\n';
}
return (0);
}
You are getting confused over array sizes. It's actually really simple, you want an array of size 5, so just use 5
in your code everywhere
int array[5];
not int array[4];
for (a=0; a<5; a++)
not for (a=0; a<=4; a++)
The second one isn't wrong, it's just easier to understand if you always use 5
instead of a mix of 4
and 5
.
Your swap function doesn't work and is not being called correctly. Your version swaps pointers not what is being pointed at. One of the more common things that newbies get wrong about pointers is getting confused about the pointer and what the pointer is pointing at. Here's how it should look:
void swap(int* a,int* b) {
int c;
c=*a;
*a=*b;
*b=c;
}
Finally you are calling the swap function wrongly. Your swap function uses pointers so you have to call it with pointers:
swap(array[f],array[f-1]);
should be
swap(&array[f],&array[f-1]);