冒泡排序算法的一般性策略:搜索整个值列,比较相邻元素,如果两者的相对次序不对,则交换它们,其结果是最大值“想水泡一样”移动到值列的最后一个位置上,这也是它在最终完成排序的值列中合适的位置。然后再次搜索值列,将第二大的值移动至倒数第二个位置上,重复该过程,直至将所有元素移动到正确的位置上。
下面是两个Java冒泡算法程序:
public class Bubble {
// 冒泡排序函数1
public static void bubbleSort1(Comparable []data){
int position,scan;
Comparable temp;
for (position = data.length-1;position>=0;position--){
for (scan=0;scan<=position-1;scan++){
if (data[scan].compareTo(data[scan+1])<0){
temp = data[scan];
data[scan] = data[scan+1];
data[scan+1]=temp;
}
}
}
}
// 冒泡排序函数2
public static int [] bubbleSort2(int [] m){
int intLenth = m.length;
/*执行intLenth次*/
for (int i=0;i<intLenth;i++){
/*每执行一次,将最小的数排在后面*/
for (int j=0; j<intLenth-i-1;j++)
{
int a = m[j];
int b = m[j + 1];
if (a < b)
{
m[j] = b;
m[j + 1] = a;
}
}
}
return m;
}
public static void main(String []args){
// 冒泡排序1
Comparable []c={4,9,23,1,45,27,5,2};
bubbleSort1(c);
for (int i=0;i<c.length;i++)
System.out.println("冒泡排序1:" +c[i]);
System.out.println("*******************" );
// 冒泡排序2
int []b = {4,9,23,1,45,27,5,2};
int []e = bubbleSort2(b);
for (int j=0;j<e.length;j++)
System.out.println("冒泡排序2:" +e[j]);
}
}
附件:http://down.51cto.com/data/2350188
----------------------------
原文链接:https://blog.51cto.com/tscjsj/84561
作者:唐大老师
程序猿的技术大观园:www.javathinker.net
[这个贴子最后由 flybird 在 2020-03-19 10:13:44 重新编辑]
网站系统异常
系统异常信息
Request URL:
http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=2909&replyID=0&skin=1&saveSkin=true&pages=1&replyNum=
java.lang.NullPointerException
如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员 。