冒泡排序

冒泡排序原理图解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class BubbleSortDemo {

public static void main(String[] args) {

// 定义一个数组
int[] arr = {24, 69, 80, 57, 13} ;

// 遍历方法
System.out.print("排序前: ");
print(arr) ;

// 排序
bubbleSort2(arr);

// 排序后的输出
System.out.print("排序后: ");
print(arr) ;
}

/**
* 优化后的冒泡排序
*/
private static void bubbleSort2(int[] arr) {

for(int x = 0 ; x < arr.length - 1 ; x++){

/*
* arr.length - 1: 目的是为了防止数组角标越界
* arr.length - 1 - x : -x目的是为了提高效率
*/
for(int y = 0 ; y < arr.length - 1 - x ; y++){
if(arr[y] > arr[y + 1]){
int temp = arr[y] ;
arr[y] = arr[y+1];
arr[y+1] = temp ;
}
}
}

}

/**
* 冒泡排序
*/
private static void bubbleSort(int[] arr) {

// 第一次排序
// arr.length - 1 目的: 防止数组角标越界
for(int x = 0 ; x < arr.length - 1 - 0; x++){

if(arr[x] > arr[ x + 1 ]){
int temp = arr[x] ;
arr[x] = arr[ x + 1];
arr[ x + 1 ] = temp ;
}
}

// 第二次排序
for(int x = 0 ; x < arr.length - 1 - 1; x++){

if(arr[x] > arr[ x + 1 ]){
int temp = arr[x] ;
arr[x] = arr[ x + 1];
arr[ x + 1 ] = temp ;
}
}

// 第三次排序
for(int x = 0 ; x < arr.length - 1 - 2; x++){

if(arr[x] > arr[ x + 1 ]){
int temp = arr[x] ;
arr[x] = arr[ x + 1];
arr[ x + 1 ] = temp ;
}
}

// 第四次排序
for(int x = 0 ; x < arr.length - 1 - 3; x++){

if(arr[x] > arr[ x + 1 ]){
int temp = arr[x] ;
arr[x] = arr[ x + 1];
arr[ x + 1 ] = temp ;
}
}

}

/**
* 遍历数组的方法
*/
public static void print(int[] arr){
System.out.print("[");
for(int x = 0 ; x < arr.length ; x++){
if(x == arr.length - 1){
System.out.println(arr[x] + "]");
}else {
System.out.print(arr[x] + ", ");
}
}
}
}
-------------本文结束感谢您的阅读-------------
0%