Java冒泡排序详解,面试必备!!!

it2025-02-11  29

文章目录

1.先要学会怎么样让两个数交换值;2.最简单的冒泡排序3.对其进行简单的优化4.最终优化 冒泡排序:我对冒泡排序的理解就是相邻两个数进行比较,确定其大小后让他们交换位置,交换后他们中的一个在和另外一个相邻的数比较,依次进行就可以确定一个最大或者最小的数,并且其位置在最后.在依次进行这样的操作直到顺序全部排好;

1.先要学会怎么样让两个数交换值;

(1).int temp = a;(推荐使用该方法) a = b; b = temp; (2).a = a^b; b = a^b; a = a^b; (3).a = a+b-(b=a);

2.最简单的冒泡排序

//引入包,用其中的toString方法来对最后的数组进行输出 import java.util.Arrays; public class Bubble { public static void main(String[] args) { int[] a = {1,5,9,8,2,3,4,8,9}; bubbleSort(a); } public static void bubbleSort(int[] a) { int temp; //因为是两两进行比较所以最后一个数没有后面的数来跟它比较所以循环次数是数组的长度-1 for(int i=0;i<a.length-1;i++) { //因为循环一次只可以确定一个数,所以要双层for循环 for(int j=0;j<a.length-1;j++) { if(a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println(Arrays.toString(a)); } }

3.对其进行简单的优化

因为一次循环以后就确定一个数的位置所以第二次循环就可以不用和这一个数进行比较,所以第二次的 循环次数可以减去上一个循环的次数即循环次数为:数组长度-1-i;

import java.util.Arrays; public class Bubble { public static void main(String[] args) { int[] a = {1,5,9,8,2,3,4,8,9}; bubbleSort(a); } public static void bubbleSort(int[] a) { int temp; for(int i=0;i<a.length-1;i++) { for(int j=0;j<a.length-1;j++) { if(a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println(Arrays.toString(a)); } }

4.最终优化

有时候在排序到一定的次数以后,我们想要的最终顺序就出来了,都是计算机还会继续在执行循环. 所以这时候我们就可以利用break来跳出循环. 怎么判断顺序有没有排好呢? 只要在循环的过程中没有执行到if()语句就说明以及是我们要的顺序了所以我们可以利用这一点 来对冒泡排序进行最后的优化;

import java.util.Arrays; public class Bubble { public static void main(String[] args) { int[] a = {1,5,9,8,2,3,4,8,9}; bubbleSort(a); } public static void bubbleSort(int[] a) { int temp; boolean judge = false; for(int i=0;i<a.length-1;i++) { for(int j=0;j<a.length-1;j++) { if(a[j]>a[j+1]) { judge = true; temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } //如果执行过if,judge=true就不会break;!是取反的意思.只有当if()里面为true在会执行if语句 if(!judge){ break; } System.out.println(Arrays.toString(a)); } }
最新回复(0)