Shell实现冒泡、选择、插入排序和二分搜索

shell 排序 搜索

# !/bin/sh
# 冒泡,选择,插入排序;
# 二分搜索

declare -a array=(‘1’ ‘5’ ‘2’ ‘100’ ‘985’ ’33’ ‘-22’ ‘-100’ ‘123’ ’56’ ’33’ ’56’ ‘101’ “999”)
echo “排序前:${array[@]}”

# 冒泡
function bubbleSort() {
for (( i = 0; i < ${#array[@]}; ++ i )); do
for (( j = ${#array[@]} – 1; j > i ; — j )); do
if (( ${array[j]} < ${array[j-1]} )); then
local -i temp=${array[j-1]}
array[j-1]=${array[j]}
array[j]=$temp
fi
done
done
echo “冒泡:${array[*]}”
}

# 选择
function selectSort() {
for (( i = 0; i < ${#array[@]}; ++ i )); do
for (( j = i + 1; j < ${#array[@]}; ++ j )); do
if (( ${array[i]} > ${array[j]} )); then
local -i temp=${array[i]}
array[i]=${array[j]}
array[j]=$temp
fi
done
done
echo “选择:${array[*]}”
}

# 选择2
function selectSort2() {
for (( i = 0; i < ${#array[@]}; ++ i )); do
local -i min=i
for (( j = i + 1; j < ${#array[@]}; ++ j )); do
if (( ${array[min]} > ${array[j]} )); then
min=$j
fi
done

if [ “$min” -ne “$i” ]; then
local -i temp=${array[i]}
array[i]=${array[min]}
array[min]=$temp
fi
done
echo “选择2:${array[*]}”
}

# 插入
function insertSort() {
for (( i = 1; i < ${#array[@]}; ++ i )); do
for (( j = i; j > 0; — j )); do
if (( ${array[j]} < ${array[j-1]})); then
local -i temp=${array[j]}
array[j]=${array[j-1]}
array[j-1]=$temp
else
break
fi
done
done
echo “插入:${array[*]}”
}

# 二分搜索
function binarySearch() {
if [ -z “$1” ]; then
return
fi

local -i minPos=0
local -i maxPos=${#array[@]}-1
local -i midPos=${#array[@]}/2
while [ $minPos -le $maxPos ]; do
if [ “$1” -eq ${array[midPos]} ]; then
echo “位置:第$midPos个”
return
elif [ “$1” -lt ${array[midPos]} ]; then
maxPos=$midPos-1
midPos=(maxPos+minPos)/2
elif [ “$1” -gt ${array[midPos]} ]; then
minPos=$midPos+1
midPos=(maxPos+minPos)/2
fi
done
echo “没有找到”
}

#bubbleSort
#selectSort
#selectSort2
insertSort
binarySearch $1

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/98392

发表评论

登录后才能评论

联系我们

400-080-6560

在线咨询:点击这里给我发消息

邮件:1823388528@qq.com

工作时间:周一至周五,9:30-18:30,节假日同时也值班