GM: Bubble sorting

From GMpedia.org Wiki

Jump to: navigation, search

The following is an example of bubble sorting in Game Maker.

[edit] GML Example

TOTAL=30;
//-----//
VAR[01]=11;
VAR[02]=6;
VAR[03]=18;
VAR[04]=17;
VAR[05]=2;
VAR[06]=3;
VAR[07]=1;
VAR[08]=19;
VAR[09]=25;
VAR[10]=20;
VAR[11]=16;
VAR[12]=5;
VAR[13]=26;
VAR[14]=27;
VAR[15]=9;
VAR[16]=21;
VAR[17]=4;
VAR[18]=15;
VAR[19]=28;
VAR[20]=22;
VAR[21]=24;
VAR[22]=7;
VAR[23]=30;
VAR[24]=10;
VAR[25]=29;
VAR[26]=14;
VAR[27]=23;
VAR[28]=8;
VAR[29]=12;
VAR[30]=13;
//-----//
sorted=false;
  • Actual Sort Action
start=1;
wrong=0;

repeat(TOTAL)
{
 if start<TOTAL
 if VAR[start]>VAR[start+1]
 {
  //Switching occurs
  tmp1=VAR[start];
  tmp2=VAR[start+1];
  VAR[start]=tmp2;
  VAR[start+1]=tmp1;
  wrong+=1;
 }
 start+=1;
}
if(wrong==0) then
{
sorted=1;
}
else
{
 sorted=0;
}
  • Now, for actually doing the action in one step, we can use the do-until command:
do
{
 ACTUAL SORT ACTION
}
until(sorted==true)

[edit] See Also

Personal tools