So I was trying to implement Cormen's pseudocode for bubble sorting but I can't seem to get it to work.
This is my approach on Cormen's pseudocode:
void BUBBLE_SORT(int a[200], int n) {
int i, j, aux;
for (i = 1; i <= n - 1; i++) {
for (j = n; j < i + 1; j++) {
if (a[j] < a[j - 1]) {
aux = a[j];
a[j] = a[j + 1];
a[j + 1] = aux;
}
}
}
}
I tried another piece of code found on the internet but the result was not different:
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
I would love to know where my comprehension failed in understanding Cormen's implementation and to get the bubble sorting to work!
There are at least three issues:
The pseudocode assumes array indices go from
1
tolength
. In C arrays are indexed from0
tolength-1
; your code doesn't correct for that.The inner loop in the pseudocode goes
downto
i+1
, but your inner loop tries to count up:should be
The pseudocode swaps
A[j]
andA[j-1]
, but your C code swapsA[j]
andA[j+1]
.