Welcome to my ASP Code Website

Bubble Sort Code Technique

If you are sorting content into an order, one of the most simple techniques that exists is the bubble sort technique. In essence you start at one end of the list, move one by one to the other end of the list, and if you ever reach a situation where two items are out of order, you swap them.

This is one of the most simple sort techniques that exists, that is taught in any basic programming course.

Let's say you have an array of Grades(5). You want to sort them so that the highest grade is at the beginning of the list, and that the lowest grade is at the end of the list. Note that this is NOT REAL CODE. This is an example of the concept, that you can apply to any language.

So you would fill Grades(5) with the values. Then you would say -

for ctr = 1 to 4
.for ctr2 = ctr + 1 to 5
..if Grades(ctr) < Grades(ctr2) then
...Temp = Grades(ctr)
...Grades(ctr) = Grades(ctr2)
...Grades(ctr2) = Temp
..end if

So in essence you have the outer loop stepping through each item but the very last one. The inner loop steps through every untried item from whereever you are in the outer loop, going forward. The two are compared and if the higher number is not "on top", the are swapped.

Let's say your array is 90 70 80 100 60

On the first time through the loop, you begin with 90 (value 1) and compare it with the others, in order. Is 90 < 70? No. Nothing happens. Is 90 < 80? No. Is 90 < 100? Yes. The 100 takes spot 1, and the 90 takes spot 4. Is 100 < 60? No. Now we have guarantee that spot #1 is definitely the largest number in the entire array.

Now we work on the second largest number. We move on to stop 2. Is 70 < 80? YES, they swap spots. Is 80 < 90? YES, they swap spots. Is 90 < 60? No, so the 90 stays in spot 2.

And so it goes, until the entire array is settled in proper order. You can of course arrange the array in ascending or descending order just by switching the < to a > !

ASP Basic Concepts