CB> (I should also point out that with most real 'bubble sorts',
CB> there will only be 'n' exchanges. Most implementations will
CB> find the highest/lowest and then exchange in the outer loop,
CB> rather than in the inner on every successful comparisons.
CB> [Well, the 'highest' will be set, but that's very different
CB> from exchanging, esp. when the data is large structures.])
What... No example!?
Now you have only one swap for each element which is out of
place. This is not really a bubble sort, though, since the
elements don't actually migrate toward their place, but just
jump there all at once. I guess it would have to be a sort
of a hyper-bubble sort.
/* bubble.c PUBLIC DOMAIN */
#include
#include
void bubblesort(int *array, int elements)
{
int outer, inner, swap, tmp, end, reverse;
reverse = (elements < 0) ? 1 : 0;
elements = reverse ? -elements : elements;
end = elements - 1;
/*
We do this so that we need not shake our fists
toward Borland International in our rage. :)
*/
for(outer = 0; outer < end; outer++)
{
swap = outer;
for(inner = outer; inner < elements; inner++)
if((array[swap] > array[inner] && !reverse)
|| (array[swap] < array[inner] && reverse))
swap = inner;
if(swap > outer)
{
tmp = array[outer];
array[outer] = array[swap];
array[swap] = tmp;
}
}
}
void show_array(int *array, int max)
{
int i;
for (i = 0; i < max; i++)
printf("%4d", array[i]);
}
int main(void)
{
int table[10] = { 70, 21, 49, 7, 63, 42, 14, 56, 35, 28 };
puts("\n\n\tThis program demostrates sorting array "
"elements into\n\tascending/descending order"
" using a simple bubble sort.");
printf("\n\n Unsorted array is ::");
show_array(table, 10);
bubblesort(table, 10);
printf("\n\n Ascending sort array ::");
show_array(table, 10);
bubblesort(table, -10);
printf("\n\n Descending sort array ::");
show_array(table, 10);
puts("\n");
getch();
return 0;
}
> ] You want me to stay current? I can barely stay awake!!......
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)
|