Algorithm Implementation/Sorting/Bubble sort

Contents

The bubble sort is also known as the ripple sort. The bubble sort is probably the first, reasonably complex module that any beginning programmer has to write. It is a very simple construct which introduces the student to the fundamentals of how sorting works.

A bubble sort makes use of an array and some sort of "swapping" mechanism. Most programming languages have a built-in function to swap elements of an array. Even if a swapping function does not exist, only a couple of extra lines of code are required to store one array element in a temporary field in order to swap a second element into its place. Then the first element is moved out of the temporary field and back into the array at the second element's position.

Here is a simple example of how a bubble sort works: Suppose you have a row of children's toy blocks with letters on them. They are in random order and you wish to arrange them in alphabetical order from left to right.

Step 1. Begin with the first block. In this case, the letter G. (Fig. 1.)

Fig. 1

Step 2. Look at the block just to the right of it.

Step 3. If the block to the right should come before the block on the left, swap them so that they are in order (Fig. 2.)

Fig. 2

If you were doing this by hand, you might just pick the blocks to be moved with one in each hand and cross your arms to swap them. Or you might move the first one out of its position temporarily, move the second one in its place, then move the first one to the now empty position (this is the difference between having a single function to do the swap, or writing some code to do it).

Step 4. Compare the next block in line with the first, and repeat step 3. Do this until you run out of blocks. Then begin step one again with the second block. (Fig. 3,4,5,6)

CLSDIMNameArray$(1000)i=0' Seed read ...READName$' Loop through and read names in data ...DOWHILEName$<>"*EOD"i=i+1NameArray$(i)=Name$READName$LOOP' The value of i is now the number of names in the array ...ArraySize=i' Bubble (or ripple) sort ...FORi=1TOArraySize-1FORj=1TOArraySize-1IFNameArray$(j)>NameArray$(j+1)THENSWAPNameArray$(j),NameArray$(j+1)ENDIFNEXTjNEXTi' Print out the sorted results ...FORi=1TOArraySizePRINTNameArray$(i)NEXTiDATACrowe,DATAAdams,DATAZimmerman,DATAGoodhead,DATASmith,DATAJones,DATA*EOD

(defunbubblesort(listpred)"Sort LIST in order of comparison function PRED."(let((i(lengthlist)))(while(>i1)(let((blist))(while(cdrb)(when(funcallpred(cadrb)(carb))(setcarb(prog1(cadrb)(setcdrb(cons(carb)(cddrb))))))(setqb(cdrb))))(setqi(1-i)))list))

ProgramBubbleSort:constMAXINTARRAY:1000;{ Set this value to fit your data needs for max array size }STARTINTARRAY:1;{ Set 1 _or_ 0; indicates the lower index of the array }TypeIntArray:Array[STARTINTARRAY..MAXINTARRAY]ofinteger;(*=================================================================================== BubbleSort is an all purpose sorting procedure that is passed an array of integers and returns that same array with the array elements sorted as desired. Parameters are used to control the sorting operation: If you want to sort the entire array, pass a value in Count that signals the number of elements you want sorted. BubbleSort will then sort Count number of elements starting with the first element in the array. If you want to sort a subset of elements within the array, pass 0 in Count and pass a beginning and ending subset index number in First and Last, respectively. The sort will be either ascending or descending as controlled by the parameter Ascend: Pass True in Ascend and the sort will be ascending. Pass False and the sort will be descending. Data: The array to be sorted. NOTE: Sample is a var and will be modified by BubbleSort, unless the array is already in a sorted state. Count: 0 _or_ the number of elements to be sorted, starting with the first element. First: The first element to be sorted in a subset of the array. Last: The last element to be sorted in a subset of the array. Ascend: Flag to indicate the sort order. True is ascending order. False is descending. Succ: Flag returns result of BubbleSort 0 = success. 1 = Failed. Parameter First has value below allowed first index value. 2 = Failed. Parameter Last has value above allowed last index value. 3 = Failed. Parameter Last has value below allowed first index value. ===================================================================================*)ProcedureBubbleSort(VarData:IntArray;Count:integer;First:integer;Last:integer;Acend:boolean;VarSucc:integer);vari,temp,s_begin,s_end,numsort:integer;sorted:boolean;Begin{ initialize for full array sort }s_begin:=STARTINTARRAY;s_end:=STARTINTARRAY+count-1;numsort:=Count;Succ:=0;{ assume success }{ check for a subset sort; check parameters for correctness }if(Count=0)thenBeginIf(First<STARTINTARRAY)thenBegin{ error: sort start index too low }Succ:=1;Exit;End;If(Last>MAXINTARRAY)thenBegin{ error: sort end index too high }Succ:=2;Exit;End;if(Last<STARTINTARRAY)thenBegin{ error: sort end index too low }Succ:=3;Exit;End;s_begin:=First;s_end:=Last;numsort:=Last-First+1;End;Ifnumsort<=1thenExit;{ only one element, so exit }IfAcendthenBegin{ do the ascending sort }Repeatsorted:=true;{ flag default is true }Fori:=s_begintos_end-1doif(Data[i]<Data[i+1])thenBegin{ swap contents of Data[i] and Data[i+1] }temp:=Data[i];Data[i]:=Data[i+1];Data[i+1]:=temp;{ set flag to indicate a swap occured; i.e., sort may not be completed }sorted:=false;End;Untilsorted;EndElseBegin{ do the descending sort }Repeatsorted:=true;{ flag default is true }Fori:=s_begintos_end-1doif(Data[i]<Data[i+1])thenBegin{ swap contents of Data[i] and Data[i+1] }temp:=Data[i];Data[i]:=Data[i+1];Data[i+1]:=temp;{ set flag to indicate a swap occured; i.e., sort may not be completed }sorted:=false;End;Untilsorted;End;End;

defbubblesort(lst):"Sorts lst in place and returns it."forpassesLeftinrange(len(lst)-1,0,-1):forindexinrange(passesLeft):iflst[index]>lst[index+1]:lst[index],lst[index+1]=lst[index+1],lst[index]returnlst

PrivateSubbubble(Nasinteger,array()asinteger)'N is the number of integers in the array''0 to N-1'DimI,J,P,TempasIntegerForI=n-1To0Step-1P=0ForJ=0ToIIfarray(J)>array(J+1)ThenTemp=array(J)array(J)=array(J+1)array(J+1)=TempElseP=P+1EndIfIfP=IthenGoTopremendNextJNextI'premend = premature ending = all integers are allready sorted'premend:EndSub

If you are dealing with a large volume of data, use the COBOL SORT using sequential files. For sorting a WORKING STORAGE table, the following example assumes that the table is already loaded. The literals "a" indicates the size of the row, and "b" how many rows in the table.