The scanf() and printf() functions are for I/O in C. Avoid them. (You are doing fine using cin and cout.) You also appear to be using an older compiler. (Borland C++?)
Your bsort() function is doing too many things. It should
not do any I/O. The
only thing it should do is
sort. If you want, make a separate function to get input for the array. Here are some prototypes to help:
1 2 3 4 5 6 7 8 9 10 11 12
|
int get_array_from_user( int a[], int max_n );
/* Asks the user for the number of elements to enter, making sure that
it is less than or equal to max_n.
Gets the elements from the user and stores them in a[].
Returns the number of elements entered by the user.
*/
void bsort( int a[], int n );
/* Sorts the first n elements of a[]. */
void print_array( int a[], int n );
/* Prints the first n elements of a[] to the standard output. */
|
A word of warning: your array is only five elements long (as per line 8). Yet you ask the user to enter a number of elements. What if the user enters 20?
Not all elements of an array need actually be
used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int main()
{
#define B_SIZE 100 /* Give the user up to 100 elements to use */
int b[ B_SIZE ];
int n; // number of elements the user gives
n = get_array_from_user( b, B_SIZE );
bsort( b, n );
print_array( b, n );
getch();
}
|
Choice of sort order is controlled by two things: the direction of your loop(s) and the condition on line 38.
You are trying to do an optimized bubble sort, but you have confused yourself with everything.
Read through here for help.
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/bubble-sort/
Remember, the OUTER loop controls how far you need to go each time:
i is where the inner loop should
stop.
The INNER loop is the bubble loop, swapping things as necessary. It should always start at the first element (0) and stop at the last (
i).
The CONDITION of the
if statement should then control your sort order. < means that lesser elements get moved toward the back (descending order). > means that greater elements get moved toward the back (ascending order).
Hope this helps.