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.
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.























