Jan 20, 2010 at 4:08pm UTC
Hi I'm trying to write a program that sorts an array using the bubble sort method. I was wondering how would I swap elements?
Jan 20, 2010 at 4:24pm UTC
Thank you.
Last edited on Jan 20, 2010 at 4:40pm UTC
Jan 20, 2010 at 4:26pm UTC
http://cplusplus.com/forum/beginner/18432/
This was a post yesterday, still in the top 20 begineer posts .... just check my last post
if you want to write your own swap it's very easy:
1 2 3 4 5 6
type temp;
type start, end;
temp = start;
start = end;
end = start;
however using swap methods already in place like Bazzy linked is easier :P
Theres also a string swap if your dealing with std::string.
Last edited on Jan 20, 2010 at 4:31pm UTC
Jan 20, 2010 at 4:40pm UTC
well Bazzy gave me a good link and it helped but ok I'll take a look. And ok.
Last edited on Jan 20, 2010 at 6:05pm UTC
Jan 20, 2010 at 6:04pm UTC
Ok I made a program but it's not printing out all the numbers I enter and it's not putting them in the right order. The problem may be in the loops that check if a number is larger then the number next door(or my program is junk).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <stdio.h>
#include <algorithm>
#include "simpio.h"
using namespace std;
#define N 8
int bubble(int arr[]);
int main()
{
int arr[N];
bubble(arr);
getchar();
return 0;
}
int bubble(int arr[])
{
int x, y;
printf("Enter 8 integers for the array 'arr'\n" );
for (x=0; x<N; x++)
{
arr[x]=GetInteger();
}
for (x=0; x<6; x++)
{
for (y=1; y<=8; y++)
{
if (arr[x] > arr[y])
{
swap(arr[x], arr[y]);
}
else
{
break ;
}
}
}
for (x=0; x<6; x++)
{
printf("\n\n%d " , arr[x]);
}
}
Last edited on Jan 20, 2010 at 6:06pm UTC
Jan 20, 2010 at 8:38pm UTC
Ok i figured out why my program wasn't printing out all the numbers. However, I am still confused about why it's not printing them out in the correct order "from least to greatest". Please help I'm really confused.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <stdio.h>
#include <algorithm>
#include "simpio.h"
using namespace std;
#define N 8
int bubble(int arr[]);
int main()
{
int arr[N];
bubble(arr);
getchar();
return 0;
}
int bubble(int arr[])
{
int x, y;
printf("Enter 8 integers for the array 'arr'\n" );
for (x=0; x<N; x++)
{
arr[x]=GetInteger();
}
for (x=0; x<6; x++)
{
for (y=1; y<=7; y++)
{
if (arr[x] > arr[y])
{
swap(arr[x], arr[y]);
}
}
}
printf("\n\n" );
for (x=0; x<8; x++)
{
printf("%d " , arr[x]);
}
}
Last edited on Jan 20, 2010 at 9:07pm UTC
Jan 20, 2010 at 11:55pm UTC
I suggest you look up the algorithm for bubble sort and compare it to yours.
Your loop starting condition on line 27 is wrong, and that is what is causing
your trouble.
Jan 21, 2010 at 1:00am UTC
Thanks you jsmith i figured it out and thanks to Bazzy and gcampton. Now i only have three programs that are due today X_X