Bubble Sort in Csh/Tcsh

// March 17th, 2011 // Posted in Shell // Tagged as , ,

Many commercial 3D applications and Compositing softwares on Unix (Linux, OSX or any other Unix) requires csh/tcsh shell to run. All this time I never go deep into tcsh until few weeks ago. I just learned the scripting side of it and to play around with it I decided to implement Bubble sort in tcsh. This is just a direct-and-naive implementation from the pseudo code on Wikipedia’s Bubble sort page. I’m sure there are rooms for improvements.

#!/bin/tcsh
#
# Bubble sort in csh/tcsh
# @author: Pietra Arumaga (arumaga@gmail.com)

set arr = (15 70 123 55 6 2 4 1)

# index of loop. in tcsh we need to keep track of our own loop
@ s = 1

# size of the array
@ n = $#arr

# check whether we need to swap or not
@ swapped = 1

while( $swapped )
    @ swapped = 0
    foreach i($arr)
        # check whether we're at the last index or not
        if($s == $n) then
            @ s = 1
            continue
        endif

        @ next_s = $s + 1
        set a = $arr[$s]
        set b = $arr[$next_s]
        # echo "loop number is $s"
        
        if($a < $b) then
            # swap it
            set temp = $arr[$next_s]
            @ arr[$next_s] = $arr[$s]
            @ arr[$s] = $temp
            @ swapped = 1
        endif
        @ s = $s + 1
    end
end

echo $arr

Ads by Amazon.com:

Please share this journal with others:

Leave a Reply