附原视频链接:【零基础 快速学Java】韩顺平 零基础30天学会Java_哔哩哔哩_bilibili
Java基础-数组、排序和查找之排序
冒泡排序
基本思想是:通过对待排序序列,从后向前(从下标较大的元素开始),依次比较相邻元素的值,若发现逆序则交换,使值较大的元素逐渐从前移向后部
冒泡排序的特点
- 每一轮排序可以确定一个数的位置,比如第一轮排序确定最大数,第二轮排序确定第二大的数的位置
- 当进行比较时,如果前面数大于后面的数,就进行交换
冒泡排序实现
用来理解即可
public class hello01 {
public static void main(String[] args) {
int[] array = {24,69,80,57,13};
int temp = 0;
for (int j = 0;j < 4;j++){
if (array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}System.out.println("==第一轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
for (int j = 0;j < 3;j++){
if (array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}System.out.println("\n==第二轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
for (int j = 0;j < 2;j++){
if (array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}System.out.println("\n==第三轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
for (int j = 0;j < 1;j++){
if (array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}System.out.println("\n==第四轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
}
}
==第一轮排序==
24 69 57 13 80
==第二轮排序==
24 57 13 69 80
==第三轮排序==
24 13 57 69 80
==第四轮排序==
13 24 57 69 80
冒泡排序实现(精简版)
public class hello01 {
public static void main(String[] args) {
int[] array = {24,69,80,57,13};
int temp = 0;
for (int i = 0; i < 4; i++) {
//精简的巧妙之处在于这里的内层循环与外层循环配合,达到递减
for (int j = 0;j < 4 - i;j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.println("\n==第"+(i+1)+"轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
}
}
}
冒泡排序实现(精简灵活版)
public class hello01 {
public static void main(String[] args) {
int[] array = {24,69,80,57,13};
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {//发现4是数组长度-1,使其灵活
for (int j = 0;j < array.length - 1 - i;j++) {//同步改正
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.println("\n==第"+(i+1)+"轮排序==");
for (int j = 0;j < array.length;j++){
System.out.print(array[j]+"\t");
}
}
}
}
还可以继续发散思维优化一下,比如数组本身就是从大到小的顺序,那么可以当某一步的时候就不排序了;或者结合之前的内容,对数组进行手动添加,练习