Bubble Sort Routine

Example scripts and tips (replaces Old Scripts & Tips archive)

Moderators: Dorian (MJT support), JRL, Phil Pendlebury

Post Reply
User avatar
Marcus Tettmar
Site Admin
Posts: 7395
Joined: Thu Sep 19, 2002 3:00 pm
Location: Dorset, UK
Contact:

Bubble Sort Routine

Post by Marcus Tettmar » Thu Nov 16, 2006 9:06 am

Bubble Sort, or Exchange Sort, is a simple sorting algorithm. Not the fastest but ok for small lists, and nice and simple. For a faster sorting algorithm look at Selection Sort or Insertion Sort.

This example uses Bubble Sort to sort a list of files returned by the GetFileList command. Swap the greater than sign on line 15 to change the sort direction.

Code: Select all

GetFileList>c:\temp\*.*,FileList,;
Separate>FileList,;,Files

Let>Max=Files_Count
GoSub>Bubble_Sort

//Sorts Files_x array
//Set Max to number of elements
SRT>Bubble_Sort
  Let>has_swapped=0
  let>i=1
  Repeat>i
         Let>next=i+1
         //change sign on next line to change direction of sort
         if>Files_%i%>Files_%next%
	     Let>store=Files_%i%
	     Let>Files_%i%=Files_%next%
	     Let>Files_%next%=%store%
	     Let>has_swapped=1
	 endif
	 Let>i=i+1
  Until>i=Max
  If>has_swapped=1
     GoSub>Bubble_Sort
  Endif
End>Bubble_Sort
Note that this subroutine is recursive. It keeps calling itself until the list is sorted.
Marcus Tettmar
http://mjtnet.com/blog/ | http://twitter.com/marcustettmar

Did you know we are now offering affordable monthly subscriptions for Macro Scheduler Standard?

Post Reply
Sign up to our newsletter for free automation tips, tricks & discounts