HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Bubblesort implementation in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
bubblesortimplementationstackoverflow

Problem

The parameters list contain the array that is passed to and the size of the array respectively. Is there anywhere I could improve my code?

void bubbleSort(int a[], int s) {
    for (int i = 1; i  a[j + 1]) {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

Solution

Performance of your implementation is \$\Theta(N^2)\$ in all cases. You can improve it by holding a boolean variable indicating whether the current pass over the array swapped at least once the neighbouring array components. If the boolean is false, the array is sorted and we can exit the sort:

void bubbleSort(int a[], int s) {
    for (int i = 1; i  a[j + 1]) {
                std::swap(a[j], a[j + 1]);
                swapped = true;
            }
        }

        if (!swapped) {
            return;
        }
    }
}


The above alternative implementation runs in linear time on almost sorted arrays.

Also, as you can see above, #include offers you a swapping routine (std::swap); why not use it?

Hope that helps.

Code Snippets

void bubbleSort(int a[], int s) {
    for (int i = 1; i < s; i++) {
        bool swapped = false;

        for (int j = 0; j < s - i; j++) {
            if (a[j] > a[j + 1]) {
                std::swap(a[j], a[j + 1]);
                swapped = true;
            }
        }

        if (!swapped) {
            return;
        }
    }
}

Context

StackExchange Code Review Q#142314, answer score: 13

Revisions (0)

No revisions yet.