Problem wth Bubble Sort Routine

Technical support and scripting issues

Moderators: JRL, Dorian (MJT support)

Post Reply
andyw101
Newbie
Posts: 2
Joined: Fri Nov 21, 2008 9:31 am

Problem wth Bubble Sort Routine

Post by andyw101 » Fri Nov 21, 2008 10:29 am

I would like to sort the contents of a Macroscript array and thought I would use the Bubble Sort routine provided elsewhere in this forum(see below):

Code: Select all

Let>inputfile=d:\names.txt
Let>outputfile=d:\names_sorted.txt

ReadFile>inputfile,NamesList
Separate>NamesList,%CRLF%,Names

Let>Max=Names_Count
GoSub>Bubble_Sort

//Write resultant list to a new file
IfFileExists>outputfile
  DeleteFile>outputfile
Endif

Let>i=1
Repeat>i
  Let>thisname=Names_%i%
  WriteLn>outputfile,k,thisname
  Let>i=i+1
Until>i=Max

Run>Notepad.exe %outputfile%

//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>Names_%i%>Names_%next%
	     Let>store=Names_%i%
	     Let>Names_%i%=Names_%next%
	     Let>Names_%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
However I can't get this example to work on my system at all, even if I use the same input file as in the original example. On my system the Bubble_Sort subrotine is called only once and then the output file is written (unsorted).

When I step through the code in the debugger it appears that the If statement below is being ignored. Even when "has_swapped"=1 the Bubble_Sort subroutine does not get called again.

If>has_swapped=1
GoSub>Bubble_Sort
Endif

I have made sure that there are no trailing spaces in my code but I still can't get this example to run on my system. I am running Macroscheduler 7.4 Pro under Windows XP. All my other scripts are working fine.

I would appreciate any thoughts on what I can do to get this routine to work

[/code]

andyw101
Newbie
Posts: 2
Joined: Fri Nov 21, 2008 9:31 am

Problem with Bubble Sort Routine

Post by andyw101 » Fri Nov 21, 2008 7:21 pm

OK - I think I have discovered part of the problem with this example of the Bubble Sort routine as currently written. The two Repeat-Until loops are using the same index (i). So when the second (Bubble_Sort) loop increments i, the code returns to the first loop (writing the output file).

I can get the Bubble_Sort routine to sort the input properly by giving the "write output" loop a different index (e.g. j), however then the output loop just writes the last field multiple (Names_Count) times.

If I manage to work out how to fix this I'll post an update - any help appreciated in the meantime

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