# How to understand Bubble Sort Pseudo code?

• 03-02-2013, 11:54 AM
Gnabster
How to understand Bubble Sort Pseudo code?
Hi,

I have difficulity understanding the Pseudo code compared to Java, i had cracked my head but still dont understand the coding, just a few lines but i couldn't get myself to fully understand.

The Pseudo Code:

for i=1 to n-1 do
for j=i to n-1 do
if x[j]>x[j+1] then
temp=x[j]
x[j]=x[j+1]
x[j+1]=temp
end {if}
end {for}
end {for}

From my understanding of this bubble sort code:

int[] x = {5, 4, 3, 2, 1};
int n = x.length;
int temp;
int counter = 0;

for (int i = 0; i < n; i++) {
// counter ++;
for (int j = i; j < n; j++) {

if (x[j] > x[j + 1]) {
temp = x[j];
x[j] = x[j + 1];
x[j + 1] = temp;
counter++;
}
}
}

for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}

System.out.println();
System.out.println(counter);

My question is:

Is the Pseudo Code same as the other bubble sort code online? This do not have the true/false checker.
I need to calculate the:

1) Best case
2) Worst case
3) Average case

for the pseudo code, in terms of Big O Notation, all bubble sort should be worst case Big O N square, best is Big O(n), average is same as worst case.
However i am unable to convince myself by looking at the pseudo code alone, any kind souls please assist if you understand the Pseudo code, Thanks in advance :(y):
• 03-02-2013, 02:54 PM
DarrylBurke
Re: How to understand Bubble Sort Pseudo code?
• 03-02-2013, 03:33 PM
JosAH
Re: How to understand Bubble Sort Pseudo code?
Quote:

Originally Posted by Gnabster
for the pseudo code, in terms of Big O Notation, all bubble sort should be worst case Big O N square, best is Big O(n), average is same as worst case.
However i am unable to convince myself by looking at the pseudo code alone, any kind souls please assist if you understand the Pseudo code, Thanks in advance :(y):

Best, average and worst case are all O(n^2); if you're just counting the number of swaps the best case is O(0) (no swaps needed if the array is already sorted), but the average and worst case are still O(n^2).

kind regards,

Jos