program BubbleSort; { This program uses different versions of } { bubble sort algorithms. } { Author: Xiannong Meng } { Date : April 29, 1998 } uses WinCrt; { uses Windows for I/O } const Max = 20; { number of array ele. } Range = 100; { upper bound of value } type IntArray = array[1..Max] of integer; procedure Swap(var n, m : integer); { swap the value of n and m } { this procedure is used by many others } var temp : integer; begin { Swap } temp := n; n := m; m := temp; end; { Swap } procedure BubbleReal( var data : IntArray; size : integer ); { This is the REAL bubble sort. In the above algorithms, } { the bubble sort may take extra, unnecessary steps. For } { example, when the list is in order already, the above } { algorithms will still go through the loops because of } { the structure of the FOR. This algorithm stops looping } { when the list is in order. It can have two versions, up} { and down. But we only show one here. } { data : the array of integers in working } { size : the actual size of the array } var sorted : boolean; { true if the list is sorted } i : integer; { loop index } begin { BubbleReal } sorted := False; { initialize to be false } while not sorted do begin { while } sorted := True; { try to see if it is true } for i := 1 to size - 1 do if (data[i] > data[i+1]) then { out of order } begin { if } Swap(data[i],data[i+1]); sorted := False; { it needs to go more loop } end; { if } end; { while } end; { BubbleReal } procedure ArrayGen( var data : IntArray; size : integer ); { this procedures generates an integer array for a given size } { that is less than or equal to the Max. The values are random} { data : an array of integer generated } { size : the given array size } var i : integer; { loop index } begin { ArrayGen } for i := 1 to size do data[i] := trunc(random(Range)) + 1; end; { ArrayGen } procedure DisplayArray( data : IntArray; size : integer ); { prints the array one by one } var i : integer; { loop index } begin { DisplayArray } writeln(' the following is the array elements '); for i := 1 to size do writeln(i,' --- ', data[i]); end; { DisplayArray } { the main variable section} var arraySize : integer; { the size of the array } arrayInfo : IntArray; { actual array } begin { main } writeln(' size of the array : '); readln(arraySize); { number of elements in the array } Randomize; { so we use different random sequence } ArrayGen(arrayInfo, arraySize); BubbleReal(arrayInfo, arraySize); writeln(' the bubble algorithm '); DisplayArray(arrayInfo, arraySize); end. { main }