This is the version of bubblesort that I use. It is *very* similar to your version, but does sort all the way through the items.
Code:
for(i = 0; i < MaxItems - 1; i++) {
for(j = i + 1; j < MaxItems; j++) {
if(Array[i] > Array[j]) {
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
//I see you're sorting a 2D array, so I'd use it like this:
/* Sorts a 2D array of floats by using a 1D temp array*/
#include <stdio.h>
#include <stdlib.h>
#define MaxRows 4
#define MaxCols 3
float myarray[MaxRows][MaxCols] = {
{3.2, 5.8, 1.6},
{9.0, 7.7, 0.1},
{4.6, 2.8, 1.3},
{6.4, 8.5, 9.9} };
void showIt(void);
int main() {
int i, j, row, col, MaxItems;
float temp;
float *Array;
printf("\nOriginal Array: \n");
showIt();
//make a new 1D array the proper size
Array = calloc(9, sizeof(float));
for(row = 0, i = 0; row < MaxRows; row++)
for(col = 0; col < MaxCols; col++) {
Array[i] = myarray[row][col]; //transfer myarray values into Array[]
++i;
}
//now sort with a great bubblesorter
MaxItems = MaxRows * MaxCols; //which should == i - 1
for(i = 0; i < MaxItems - 1; i++) {
for(j = i + 1; j < MaxItems; j++) {
if(Array[i] > Array[j]) {
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
//And then transfer it right back to where it should be in myarray
for(row = 0, i = 0; row < MaxRows; row++) {
for(col = 0; col < MaxCols; col++) {
myarray[row][col] = Array[i];
++i;
}
}
printf("\nSorted Array: \n");
showIt();
printf("\n\n\t\t\t press enter when ready \n");
i = getchar();
free(Array);
return 0;
}
void showIt(void) {
int r, c;
for(r = 0; r < MaxRows; r++) {
for(c = 0; c < MaxCols; c++)
printf("%3.1f ", myarray[r][c]);
printf("\n");
}
}
On small arrays, this is a very fast sorter.
It looks like a lot of code, but it is astoundingly fast. I use this technique in my Sudoku solver. (except I use a static array, not a
dynamic one.)