A Better Version of Bubble Sort

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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist