Close observation of the Bubble Sort Algorithm surfaces some inefficient
procedures. Every time the Bubble Sort Algorithm swaps data, the entire
data string and possibly an entire database record is swapped in memory.
If the target machine has a small CPU cache and a slow BUS, you will
want to use pointers.
On an entirely random and unsorted database, a single record may be
swapped multiple times. A more efficient way of doing this is to use
pointers. Assign an address in memory that will be an representation of
the record but not actually the record. Then, upon swapping the data,
simply swap around the pointers. Once the pointers are sorted accordingly,
then sort the database according to the pointers in memory. You can implement
a system of pointers that may only take up one byte in memory. This is much
more efficient than swapping entire records multiple times.
Imagine a record of pointers being similar to the DOS File Allocation
Table (FAT). When you move files from one folder to another, the
hard-disk simply re-arranges the FAT, not the files. The FAT is simply
a record of pointers to files. They are faster to re-arrange than large
files on the hard-disk.
begin bubble sort:
NAMES_LIST = a list of names to sort.
SWAPPED light is OFF.
REPEAT This. /At least once/
SWAPPED light is OFF.
COUNT from 1 TO END of NAMES_LIST
IF NAMES_LIST X > NAMES_LIST X+1 /swap/
TEMP = NAMES_LIST X ->->->->->->->->|
NAMES_LIST X = NAMES_LIST X+1 |
NAMES_LIST X+1 = TEMP <-<-<-<-<-<-<|
SWAPPED light is ON.
IF NOT END of NAMES_LIST continue COUNT
END count.
WHILE the SWAPPED light is ON. /Go back to 'REPEAT This'/
end bubble-sort.
-----------------------------------------------------------------------------
JavaScript Code:
function bubblesort(arg) {
var swapped = false
do {
swapped = false
for(var i=0;i arg[i+1]) {
swap(arg,i)
swapped = true
}
}
} while(swapped) //until(!swapped)
}
function swap(arg,i) {
var temp = arg[i]
arg[i] = arg[i+1]
arg[i+1] = temp
}
Pascal implementation of the Bubble Sort algorithm (procedural).
Procedure BubbleSort(Var Employee: EmployeeArray; Choice: Integer; Top: Integer);
Var I: Integer;
Swapped: Boolean;
Begin
Repeat
Swapped:=false;
For I:=1 to (Top-1) Do
Begin
If Employee[I].GrossPay > Employee[I+1].GrossPay
Then
Begin
Swap(Employee, I);
Swapped:= true
End;
End;
Until not Swapped;
End;
Procedure Swap (Var Employee: EmployeeArray; I: Integer);
Var Temp:EmployeeRecord;
Begin
Temp:= Employee[I];
Employee[I]:= Employee[I+1];
Employee[I+1]:= Temp;
End;