osvimer
1/21/2016 - 12:53 AM

## my_sort.sh

``````#!/bin/bash
#
# description : four sorting algorithms in bash shell
# author      : Junjie Huang, acmhjj@gmail.com
# create      : 2016 JAN 20
# modifty     : 2016 JAN 21
#

arr=(5 2 7 4 8 0 6 3 1 9)

#冒泡排序
function bubble_sort(){
for ((i = 0; i < 9; i++)); do
for ((j = i + 1; j < 10; j++)); do
if [ \${arr[i]} -gt \${arr[j]} ]; then
tmp=\${arr[i]}
arr[i]=\${arr[j]}
arr[j]=\${tmp}
fi
done
done
}

#选择排序
function selection_sort(){
for ((i=0;i<9;i++)); do
min_pos=\${i}
min_value=\${arr[i]}
for ((j=i+1;j<10;j++)); do
if [ \${arr[min_pos]} -gt \${arr[j]} ]; then
min_pos=\${j}
min_value=\${arr[j]}
fi
done
if [ \${min_pos} -ne \${i} ]; then
tmp=\${arr[i]}
arr[i]=\${min_value}
arr[min_pos]=\${tmp}
fi
done
}

#插入排序
function insertion_sort(){
for ((i=1; i<10; i++)); do
if [ \${arr[i]} -lt \${arr[i-1]} ]; then
temp=\${arr[i]}
for ((j=i-1; j>=0 && arr[j]>temp; j--)); do
arr[j+1]=\${arr[j]}
done
arr[j+1]=\${temp}
fi
done
}

#快速排序
function quick_sort(){
local i=\$1
local j=\$2

if [ \$1 -gt \$2 ]; then
return
fi

while [ \${i} -ne \${j} ]; do
while [ \${arr[j]} -ge \${arr[\$1]} ] && [ \${i} -lt \${j} ]; do
j=\$[\$j - 1]
done
while [ \${arr[i]} -le \${arr[\$1]} ] && [ \${i} -lt \${j} ]; do
i=\$[\$i + 1]
done
if [ \${i} -lt \${j} ]; then
temp=\${arr[i]}
arr[i]=\${arr[j]}
arr[j]=\${temp}
fi
done
temp=\${arr[i]}
arr[i]=\${arr[\$1]}
arr[\$1]=\${temp}
quick_sort \$1 \$[\$i - 1]
quick_sort \$[\$1 + 1] \$2
}

quick_sort 0 9

for ((i=0; i<10; i++)); do
echo \${arr[i]}
done
``````