Tutorial 6
In this tutorial, we are going to familiarize ourselves with some sorting algorithms using shell programming. We will deal with bubble sort and insertion sort. We will also create some scripts ourselves as exercise. Use Vi, Emacs or Pico for editing the scripts. Login to one of the following Unix servers:
cs1.utdallas.edu
cs2.utdallas.edu
Use PuTTY or Xmanager for logging on as you learnt in Tutorial 1.
First example script: Bubble Sort
In our first example, we will write a script which will sort and print an array of integers or characters whose size is dynamically determined. Open your favorite Unix editor and type in the following script:
The bubble sort algorithm can be accessed through Bubble Sort.
Here is the script:
|
#!/bin/bash
# values. |
Type the script in the editor and save the file as bubblesort.sh. Run it after assinging execute permission:
{cs1:~} chmod +x
bubblesort.sh
{cs1:~} bubblesort.sh
Input unsorted numbers --
-1 10 200 -1 20 2 -100
Sorted Output --
-100 -1 -1 2 10 20 200
Second example script: Insertion Sort
In this example, we will write a script which will sort and print an array of integers or characters whose size is dynamically determined. Open your favorite Unix editor and type in the following script:
The insertion sort algorithm can be accessed through Insertion Sort.
Here is the script:
#!/bin/bash
echo "Enter numbers to be sorted"
read -a ARRAY
min=0
count=${#ARRAY[@]}
c=`expr $count - 1`
for ((i=0;$i<=$c;i++)) do
min=$i
index=${ARRAY[$i]}
for ((j=$i;$j<=$c;j++)) do
if [
${ARRAY[$j]} -le $index ]
then
min=$j
index=${ARRAY[$j]}
fi
done
ARRAY[$min]=${ARRAY[$i]}
ARRAY[$i]=$index
done
echo "=============================="
for ((i=0;$i<=$c;i++)) do
echo ${ARRAY[$i]}
done
echo "=============================="
Type the script in the editor and save the file as insertionsort.sh. Run it after assigning executes permission:
{cs1:~} chmod +x insertionsort.sh
{cs1:~} insertionsort.sh
Enter numbers to be sorted
-1 10 200 -1 20 2 -100
==============================
-100
-10
-1
2
10
20
200
==============================