LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 920|回复: 4

bash 冒泡法排序

[复制链接]
发表于 2004-12-7 18:47:00 | 显示全部楼层 |阅读模式
要求:
A shell script which prints the given numerical arguments in descending order.

源码:
#!/bin/bash
total=$#
if [ $total -lt 1 ]
then
echo "Usage: $0 arug1 ..."
else
cou=0
while [ $1 ]
do
  A[$cou]=$1
  cou=`expr $cou + 1`
  shift
done
i=0
j=0
iend=`expr $total - 1`
jend=$total
while [ $i -lt $iend ]
do
j=`expr $i + 1`
while [ $j -lt $jend ]
do
  if [ ${A[$i]} -lt ${A[$j]} ]
  then
  tmp=${A[$i]}
  A[$i]=${A[$j]}
  A[$j]=$tmp
  fi
  j=`expr $j + 1`
done
i=`expr $i + 1`
done
cou=0
while [ $cou -lt $total ]
do
echo ${A[$cou]}
cou=`expr $cou + 1`
done
fi

运行:
e0300481@shell:~/scripts$ . Q15 9 3 4 2 7 0
9
7
4
3
2
0
e0300481@shell:~/scripts$

第一次用bash写这么“长”的程序,请大家多多指点:p
发表于 2004-12-7 21:35:08 | 显示全部楼层
#!/bin/bash
echo $* | tr ' ' '\n' | sort -g


为啥要搞这么长?
 楼主| 发表于 2004-12-7 22:09:32 | 显示全部楼层
用C编程习惯了……
还未领会shell script的精华 -_-b

btw.
应该是
!/bin/bash
echo $* | tr ' ' '\n' | sort -g -r

desending order 降序
发表于 2004-12-8 15:20:07 | 显示全部楼层
楼主说的是冒泡排续,是一种算法.二楼的是bash提供的功能,不要弄错了哦
发表于 2004-12-9 11:19:31 | 显示全部楼层
最初由 levent 发表
楼主说的是冒泡排续,是一种算法.二楼的是bash提供的功能,不要弄错了哦

C的精髓在于"算法"的精确底层实现,而Shell是高层应用,它的精髓在于命令行的构建,操作对象是"命令"。实现同样的任务,但两者的做法是不一样的。
越俎代庖是不可取的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表