/* Bubble sort an array of 10 ints into ascending order. The for loop in lines 29-38 will move the array elements part of the way into the correct order. If some moves were made, it means that we should execute this for loop again to see if additional moves will be made. In this case, flag is set to 1 to make the do-while loop execute the for loop again. If no moves were made, it means that the elements are already in order. In this case, flag remains 0 and the do-while loop terminates. */ #include main() { int a[10]; int i; /* index into the array */ int flag; /* set to 1 to ensure one more trip */ int temp; /* temporary storage for exchanging values */ /* Initialize the array with the numbers to be sorted. */ printf("Type %d numbers. Press RETURN after each one.\n", 10); for (i = 0; i < 10; ++i) { scanf("%d", &a[i]); } /* Bubble sort the array into ascending order. */ do { flag = 0; for (i = 0; i < 9; ++i) { if (a[i] > a[i+1]) { temp = a[i]; /* swap a[i] and a[i+1] */ a[i] = a[i+1]; a[i+1] = temp; flag = 1; } printf("debug: i == %d\n", i); } } while (flag == 1); /* Output the array. */ for (i = 0; i < 10; ++i) { printf("%11d\n", a[i]); } }