Sorting numeric variables with Batch

A little script to sort three variables. Unfortunately I had no time to make a bubble sort 🙁

@echo off
setLocal EnableDelayedExpansion
set _a=%random%
set _b=%random%
set _c=%random%
set _a
set _b
set _c
call :changeasc _a _b
call :changeasc _b _c
call :changeasc _a _c
set _a
set _b
set _c
goto exit
if !%1! gtr !%2! set /a %1^^=%2^^=%1^^=%2
goto :eof

Exchanging the variables is performed by three XORs in a row

  • a=a XOR b
  • b=b XOR a
  • a=a XOR b
and the variables exchanges their values.
  • a =  7 ^ 0111
  • b= 10 ^ 1010
a = 0111 xor 1010 = 1101 = a
b = 1010 xor 1101 = 0111 = b
a = 1101 xor 0111 = 1010 = a (these variable (new a and b) are the results from the first two lines)
CMD says to XOR variables you have to write set /a variable ^=variable. Unluckily the ^ is a special character which we must escape.

By the way %random% is super effectiv on my computer (fast clicking the batch file):

  1. run:_a=234,_b=17788,_c=30123
  2. run:_a=241,_b=18852,_c=20748
  3. run:_a=241,_b=18852,_c=20748
  4. run:_a=241,_b=18852,_c=20748
  5. run:_a=241,_b=18852,_c=20748
  6. run:_a=244,_b=5844,_c=29600
  7. run:_a=244,_b=5844,_c=29600
  8. run:_a=247,_b=7581,_c=23708
  9. run:_a=247,_b=7581,_c=23708
  10. run:_a=247,_b=7581,_c=23708

Also check this information about RANDOM

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.