- 先循环一次将数组内部的最大元素排序到最后一位
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr1 = {2, 5, 8, 4, 3};
for (int i = 0; i < arr1.length - 1 ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
System.out.println(Arrays.toString(arr1)); // [2, 5, 4, 3, 8]
}
}
- 我们在上面经过一次循环将8排序到了最后一位, 如果想将5排序到倒数第二位, 应该再走一次循环
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr1 = {2, 5, 8, 4, 3};
for (int i = 0; i < arr1.length - 1 ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
System.out.println(Arrays.toString(arr1)); // [2, 5, 4, 3, 8]
// 这里 -2 的目的是因为最后一位已经是排列的好的了, 不用再排序了
for (int i = 0; i < arr1.length - 2 ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
System.out.println(Arrays.toString(arr1)); // [2, 4, 3, 5, 8]
}
}
- 思考一下, 如果我想将剩下的 3 个元素排序是不是还要执行三遍的循环呢
import java.util.Arrays;
public class Main {
// 排序方法实现
private static void sort (){
int[] arr1 = {2, 5, 8, 4, 3};
for(int j = 0; j < arr1.length - 1; j++){
for (int i = 0; i < arr1.length -1 - j ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
}
System.out.println("排序结果" + Arrays.toString(arr1));
}
public static void main(String[] args) {
int[] arr1 = {2, 5, 8, 4, 3};
for (int i = 0; i < arr1.length - 1 ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
System.out.println(Arrays.toString(arr1));
for (int i = 0; i < arr1.length - 2 ; i++){
int tag ;
if(arr1[i] > arr1[i+1]){
tag = arr1[i];
arr1[i] = arr1[i+1];
arr1[i+1] = tag;
}
}
System.out.println(Arrays.toString(arr1));
Main.sort();
}
}
标签:java,实现,++,Arrays,冒泡排序,int,length,tag,arr1
From: https://www.cnblogs.com/shiazhen/p/16654380.html