A Better Version of Bubble Sort

This version of bubble sort stops when there are no more exchanges and it also sorts a smaller range each time.

void bubbleSort3(int x[], int n) {  bool exchanges;  do {    n--;               // make loop smaller each time.    exchanges = false; // assume this is last pass over array    for (int i=0; i x[i+1]) {        int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;        exchanges = true;  // after an exchange, must look again      }    }  } while (exchanges);}

There’s one disadvantage: after the first pass it may not be necessary to examine the entire range of the array?only from where the lowest exchange occurred to where the highest exchange occurred.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: