Monday, September 3, 2007

Advanced Batch File Techniques - Bubble Sort

@echo off
set /a count=0

:loop
echo %1 > _%count%.var
set /a count=count+1
shift
if "%1" == "" goto :startSort
goto loop

:startSort
set /a total=%count%-1

:RestartSort
set /a count=0

:sortLoop
set /a next=%count%+1
call :swap %count% %next%
set /a count=count+1
if "%swapped%" == "true" goto :RestartSort
if "%count%" == "%total%" goto :output
goto :sortLoop

:swap
set /P var1="" < _%1.var
set /P var2="" < _%2.var
if /I %var1% LEQ %var2% goto noSwap
ren _%1.var _temp.var
ren _%2.var _%1.var
ren _temp.var _%2.var
set swapped=true
goto :eof

:noSwap
set swapped=
goto :eof

:output
for /L %%i in (0,1,%total%) do call :showval %%i

:cleanup
erase *.var
set next=
set offset=
set total=
set count=
set var=
set var1=
set var2=
goto :eof

:showval
type _%1.var
goto :eof

No comments: