tonglin0325的个人主页

Java排序算法——冒泡排序

 

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
package com.interview.sort;

import java.util.Arrays;

class ArraysBubble {
private int[] arrays;
private int curNum;

public ArraysBubble(int max) { //建立一个max长度的空数组
super();
arrays = new int[max];
curNum = 0;
}

public void insert(int value) { //往空的数组里面增加元素
arrays[curNum] = value;
curNum++;
}

public void display() { //显示数组
System.out.println(Arrays.toString(arrays));
}

private void swap(int one, int two) { //交换
int temp = arrays[one];
arrays[one] = arrays[two];
arrays[two] = temp;
}

public void BubbleSort() {
for (int i = 0; i < curNum; i++) {
for (int j = i + 1; j < curNum; j++) {
if (arrays[j] < arrays[i]) {
swap(i, j);
}
}
}
}

// public void BubbleSort() {
// int out, in;
// for (out = curNum - 1; out > 0; out--) { //curNum自加为下一次插入做做准备,在此应减去1
// for (in = 0; in < out; in++) { //从最后一个数开始,和前面每一个数比较,把最大的移到最后
// if (arrays[in] > arrays[out]) {
// swap(in, in + 1);
// }
// }
// }
//
//
// }
}

public class BubbleSort {

public static void main(String[] args) {
// TODO 自动生成的方法存根
int maxSize = 100;
ArraysBubble arrays_demo = new ArraysBubble(maxSize);
arrays_demo.insert(58);
arrays_demo.insert(57);
arrays_demo.insert(56);
arrays_demo.insert(60);
arrays_demo.insert(59);
arrays_demo.display();
arrays_demo.BubbleSort();
arrays_demo.display();
}

}

 输出

1
2
3
[58, 57, 56, 60, 59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[56, 57, 58, 59, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]