Logic for the Bubble Sort:

Assume that we are starting out with the numbers 5, 6, 2, 3, 4 in that order.

SUB1 will point to the first thing we want to compare and SUB2 will point to the second. END-PT is set to how many numbers we are checking - since we are starting out at 5 numbers END-PT is initially set to 5.

FLIP-CT is incremented every time we flip - if we go through an entire pass without flipping we can assume the sort to be done. Otherwise the sort is done when we have done 4 passes (because there are 5 numbers to be sorted).

Pass 1:

BEFORE

PROCESSING

SUB1

SUB2

END-PT

FLIP-CT

AFTER

5

6

2

3

4

Initialize

1

2

5

0

5

6

2

3

4

5

6

2

3

4

Compare:

SUB1 pts at 5

SUB2 pts at 6

5<6 leave alone

1

2

5

0

5

6

2

3

4

5

6

2

3

4

Compare:

SUB1 pts at 6

SUB2 pts at 2

6 not < 2 so flip

2

3

 

1

5

2

6

3

4

5

2

6

3

4

Compare:

SUB1 pts at 6

SUB2 pts at 3

6 not < 3 so flip

3

4

 

2

5

2

3

6

4

5

2

3

6

4

Compare:

SUB1 pts at 6

SUB2 pts at 4

6 not < 4 so flip

4

5

 

3

5

2

3

4

6

5

2

3

4

6

SUB2>END-PT so pass complete

6 locked at end so 1 subtracted

from END-PT for Pass 2

5

6

     

 

 

Pass 2:

BEFORE

PROCESS

SUB1

SUB2

END-PT

FLIP-CT

AFTER

5

2

3

4

6

Initialize

1

2

4

0

5

2

3

4

6

5

2

3

4

6

Compare:

SUB1 pts to 5

SUB2 pts to 2

5 not < 2 so flip

1

2

 

1

2

5

3

4

6

2

5

3

4

6

Compare:

SUB1 pts to 5

SUB2 pts to 3

5 not < 3 so flip

2

3

 

2

2

3

5

4

6

2

3

5

4

6

Compare:

SUB1 pts to 5

SUB2 pts to 4

5 not < 4 so flip

3

4

 

3

2

3

4

5

6

2

3

4

5

6

Compare:

SUB1 pts to 5

SUB2 pts to 6

5<6 leave alone

4

5

   

2

3

4

5

6

2

3

4

5

6

SUB2>END-PT so pass complete

5 & 6 locked at end so 1 subtracted

from END-PT for Pass 3

5

6

     

Pass 3:

BEFORE

PROCESS

SUB1

SUB2

END-PT

FLIP-CT

AFTER

2

3

4

5

6

Initialize

1

2

3

0

2

3

4

5

6

2

3

4

5

6

Compare:

SUB1 pts to 2

SUB2 pts to 3

2<3 leave alone

1

2

   

2

3

4

5

6

2

3

4

5

6

Compare:

SUB1 pts to 3

SUB2 pts to 4

3<4 leave alone

2

3

   

2

3

4

5

6

2

3

4

5

6

SUB2>END-PT so pass complete

4 & 5 & 6 locked at end so 1 subtracted

from END-PT for Pass 4

However no flips so no need for pass 4 - SORT ENDS

3

4

   

2

3

4

5

6