-
bubble sort
how do I make a bubble sort so it sorts the numbers in an array from smallest to highest ... my sorce code is below ... thanks for any help you can give me.
snofink
//assume the array is 5 numbers in size
for( int a=0; i<5; i++ )
{
for( i=0; i<5; i++ )
{
if( i > 0 )
{
if( set[a] < set[a-1] )
{
temp = set[a-1];
set[a-1] = set[a];
set[a] = temp;
}
}
}
}
-
the following is your code with a few adjustments. I only tested the case that you see in set, but I think its correct (famous last words).
Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
//assume the array is 5 numbers in size
int set[] = { 6,12,1,8,0 };
int temp = 0;
for( int a = 0; a < 5; a++ )
{
for( int i=4; i >= a; i-- )
{
if( set[i] < set[i-1] )
{
temp = set[i-1];
set[i-1] = set[i];
set[i] = temp;
}
}
}
cout << set[0] << " " << set[1] << " " << set[2] << " " << set[3] << " " << set[4] << endl;
return 0;
}
-
This is something I've never seen - main() taking arguments. Also, if stdafx.h is a user defined header, wouldn't you need to post that as well? I've never seen a regular header file in quotes before, only user defined ones.
Bubble sort has several examples in textbooks.
-
The arguments in main are so a user can pass arguments to the program from the command line such as switches.
prog.exe /x /y
int main(int argc, char* argv[])
argc is an integer containing a count of arguments being passed to the program. It is always 1 or greater.
argv is an array of null terminated strings representing the command line arguments entered by the user of the program. By convention argv[o] is the command with which the program is invoked, argv[1] is the first command-line argument, and so on, until argv[argc], which is always NULL.
stdafx.h is generated by VC++ for precompiled headers. Precompiled headers save the compiler from having to parse the header (.H) files for each .CPP file in which the headers are included. It’s much faster to load the precompiled header, large as it is, into memory than to parse the 50,000+ lines of the system header files for each .CPP module you compile. Since the system headers are so large, it doesn’t usually make sense to include your project’s own headers in the precompiled header, especially if they’re changing. (One little change in a precompiled header means that the entire project has to be rebuilt from scratch, regardless of whether the sources have changed.) However, if your project has headers (such as headers for your own libraries) that don’t change, including them in your precompiled header can speed up builds somewhat.
-
thanks
thank you for your help =P