dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C
Expertise: Advanced
Oct 25, 2003

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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<n; i++) {
      if (x[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.
Wael Salman
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date