Did I correctly translate this pseudocode into Java? I am particularly looking at line 3 in the pseudocode for this sorting algorithm.
Here is the pseudocode that I am attempting to translate:
Sort-Array(A)
for i = 1 to (A.length – 1)
for j = (i + 1) to A.length
if (A[j] > A[i])
// swap A[i] and A[j]
buffer = A[j]
A[j] = A[i]
A[i] = buffer
My translation:
static void bubbleSort(int array[]) {
int size = array.length;
// loop to access each array element
for (int i = 1; i < size - 1; i++)
// loop comparing the array elements
for (int j = i + 1; j < size; j++)
// compare two adjacent elements
// changing > to < to sort in either order
if (array[j] > array[i]) {
// swapping elements.
int buffer = array[j];
array[j] = array[i];
array[i] = buffer;
}
Yes, but there is one mistake. In the pseudocode you start with i = 1, because in pseudocode we dont start counting at 0. in your programm you have to start at 0, because the first element of an array start at array[0], not array[1].