The bubble sort presented in class is inefficient for large arrays. Make the following simple modifications to improve the performance of the bubble sort.
#include <stdio.h>
#define SIZE 10
int main ()
{
int a [ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i;
int pass;
int hold;
printf("Data items in original order\n");
for (i =0; i < SIZE; i++) {
printf("%4d",a[ i ]);
}
for (pass=1; pass < SIZE; pass++) {
for (i=0; i< SIZE -1; i++){
if (a [i] > a[i+1]) {
hold = a[ i ];
a[ i ] = a[i+1];
a[i+1]=hold;
}
}
}
printf("\nData items in ascending order\n");
for (i = 0; i <SIZE; i++) {
printf("%4d",a[i]);
}
printf("\n");
return 0;
}
a. After the first pass, the largest number is guaranteed to be in the highest-numbered element of the array; after the second pass, the two highest numbers are “in place,” and so on. Instead of making nine comparisons on every pass, modify the bubble sort to make eight comparisons on the second pass, seven on the third pass and so on.
b. The data in the array may already be in the proper order or near-proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass if any swaps have been made. If none has been made, then the data must already be in the proper order, so the program should terminate. If swaps have been made, then at least one more pass is needed.
What mowali says is a different method of sorting . You musn't even relate yours to bubble sort . It is imperative that bubble sort takes n-1 passes as the algorithm defines .
BTW why stick to bubble sort??? As far as I know it is one of the most inefficient ways of sorting . It takes O (n2) while quicksort takes O ( n log (n) ).