首页 技术 正文
技术 2022年11月11日
0 收藏 691 点赞 3,700 浏览 1627 个字

冒泡排序:可以想象成煮开水,气泡在瓶底的时候是比较小的,到达水面的时候达到最大。

冒泡排序的思想:先确定是升序还是降序,这里升序为例。每两个相邻的数字进行比较,前一个数字比后面一个数字大,就将两个数字交换位置,否则位置不变继续下一个。一轮排序之后,数组中最大的数字一定是在最后。

伪代码:

    数组a={10,9,8,7,6,5,4,3,2,1}

      for(int i=0;i<a.length;i++){

          for(int j=0;j<a.length-i-j;j++){   //为什么是j<a.length-i-1; 先解释减1,到数据组的最后两个数的时候a[j]  和 a[j++] 进行比较,当没有减1的时候会下标越界。为什么要减i,每一轮排序都会产生(i+1)个已经排好序的数据

              交换数据:swap(a[j],a[j++])

                      }

          }

      输出排序完的数据:升序

代码:

package math;/**
* Created by Administrator on 2018/3/2.
* 冒泡排序
* 思想:冒泡排序就是将相邻的两个相比较,按照定义的规则,决定将大数放在前面还是后面,然后进行交换顺序,
* 每一次排序都会将那一次最大的或者最小的数排在最后
* 冒泡排序的时间复杂度:o(n2)
*/
public class BubbleTest { public static void main(String[] args){
/* //控制台进行输入数据
Scanner s=new Scanner(System.in);
//输入的数字存放到数组中
Integer array[]=new Integer[10];
Integer count=0;
System.out.println("请输入十个数:");
while (s.hasNextInt()){
Integer tempNum=s.nextInt();
array[count++]=tempNum;
if(count>9){
break;
}
}
System.out.println("输入的十个数是:");
for(int i=0;i<10;i++){
System.out.print(array[i]+",");
}*/
Integer count=100000;
Integer array[]=new Integer[count];
for(int w=0;w<array.length;w++){
array[w]=count--;
} /*冒泡排序*/
long startTime=System.currentTimeMillis();
System.out.println(startTime);
for(Integer i=0;i<array.length;i++){
for(Integer j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
Integer temp;
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
/* System.out.println("第"+i+"次排序之后的顺序:");
for(Integer k=0;k<array.length;k++){
System.out.print(array[k]+",");
}*/
}
Long endTime=System.currentTimeMillis();
System.out.println(endTime);
System.out.println("总耗时==="+(endTime-startTime));
/* System.out.println("排序之后的顺序:");
for(Integer f=0;f<array.length;f++){
System.out.print(array[f]+",");
}
*/ }}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,135
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,603
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,446
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,220
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,855
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,941