-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
82 lines (73 loc) · 2.19 KB
/
BubbleSort.java
File metadata and controls
82 lines (73 loc) · 2.19 KB
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
package com;
import java.math.BigDecimal;
/**
* @author <a href="mailto:daiju3@crnet.com.hk">daiju3</a>
* @version 1.0.0
* @description 冒泡排序算法以及优化
* @since 2018/6/25 19:46
*/
public class BubbleSort {
public static final BigDecimal FINAL_NUMBER = BigDecimal.valueOf(100);
public static void main(String[] args) {
int a[]={111,2,3234,4323,24,421,999,65656,3332,44,55,333};
bubbleSort3(a);
for(int i:a){
System.out.println(i);
}
}
public static void exchange(Integer a){
a=2222;
}
public static void bubbleSort1(int a[]){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
//优化1
public static void bubbleSort2(int a[]){
for(int i=0;i<a.length;i++){
boolean isExchange=true;
for (int j=0;j<a.length-i-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
isExchange=false;
}
}
if(isExchange){
break;
}
}
}
public static void bubbleSort3(int a[]){
int temp=0;
//记录最后一次交换的位置
int lastExchangeIndex=0;
//无序数列的边界,每次只需要比较到这里为止
int sortBorder=a.length-1;
for(int i=0;i<a.length;i++){
//有序标记,每一轮的初始值为true
boolean isSort=true;
for(int j=0;j<sortBorder;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
isSort=false;//有元素交换,所以不是有序,标记变为false
lastExchangeIndex=j;//把无序数列的边界更新为最后一次交换元素的位置
}
}
sortBorder=lastExchangeIndex;
if(isSort){
break;
}
}
}
}