码迷,mamicode.com
首页 > 编程语言 > 详细

shell脚本排序(冒泡排序)

时间:2015-04-20 09:27:06      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

#/bin/bash
a=(9 84 51 0 345 1 2 34 1 0) 
#自己定义一个数组
temp=
for((i=0;i<10;i++))
{
	for((j=i;j<10;j++))
		{
		  x=${a[$i]}
			if test $x -ge ${a[$j]}
				then
			  temp=${a[$i]}
				a[$i]=${a[$j]}
				a[$j]=$temp
			fi	
		}
}
for((k=0;k<10;k++))
{
	echo -n ${a[$k]} "  "
}
echo

上面以自定义固定数组进行排序,下面是用户自定义输入数组进行排序。

#/bin/bash

a=`expr $# + 1`
#expr是一个计算操作,$#是参数个数,$#+1是因为$0没有存储参数.
temp=
for((i=1;i<$a;i++))
{
	b[$i]=$1
	shift 1	
}
for((i=1;i<$a;i++))
{
	for((j=i;j<$a;j++))
		{
			x=${b[$i]}
			if test $x -ge ${b[$j]}
			then
				temp=${b[$i]}
				b[i]=${b[$j]}
				b[j]=$temp
				#相当与冒泡排序
			fi
		}
}
for((k=1;k<$a;k++))
{
	echo -n ${b[$k]} " "
	#不换行显示
}
echo
~$./a.out 7 6 56 4 3

 ~$3  4  6  7  56

shell脚本排序(冒泡排序)

标签:

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/45145905

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!