Monday, January 2, 2012

Bubblesort in C++/C

The code for bubblesort in c++ is relativly straightforwar:
 
void bubblesort(int *A, int length) {
    for (int i = length; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (A[j] > A[j + 1]) {
                int tmp = A[j];
                A[j] = A[j + 1];
                A[j + 1] = tmp;
            }
        }
    }
} 
 
Two for loops and a comparison between two elements of the loop and a swap. When you know how bubblesort works you can write it in very many languages even if you're not good at them.

No comments:

Post a Comment