Optimized bubble sort to for an integer array - C++ Data Structure

C++ examples for Data Structure:Sort

Description

Optimized bubble sort to for an integer array

Demo Code

#include <cstdlib>
#include <iostream>

void printArray(int[], int);

const int limit = 10;

int main(int argc, const char *argv[]) {
    int n[limit] = {};

    // randomise elements of n
    for (int i = 0; i < limit; ++i) {
        n[i] = rand() % 100;/*from   w ww .  j a  v  a2s .co m*/
    }
    printArray(n, limit);

    // BUBBLE SORT
    for (int i = 0, swaps = 0; i < limit; swaps = 0, ++i) {
        // inner loop limit can decrease by i as the last value on each pass
        // will be in the correct order
        for (int j = 0; j < limit - i; ++j) {
            // swap values if needed
            if (n[j] > n[j + 1]) {
                int temp = n[j];

                n[j] = n[j + 1];
                n[j + 1] = temp;

                ++swaps;
            }
        }
        // if no swaps made no need to make another pass
        if (swaps == 0) {
            break;
        }
    }
    printArray(n, limit);

    return 0;
}

void printArray(int n[], int sizeOfN) {
    for (int i = 0; i < sizeOfN; ++i) {
        std::cout << n[i] << std::endl;
    }
}

Result


Related Tutorials