冒泡排序也就是每次将最大或最小的元素往上交换,就像气泡一样往上飘。基本学习编程的同学入门都会,就不多说了,可以自行查阅,比较简单。
代码如下:
/**
* @Description: 冒泡排序
* 这里采用的是从左至右
* @Param: []
* @return: void
*/
public void bubbleSort() {
boolean tempSwapped;
DataNode tempNode;
for (int i = length - 1; i > 1; i--) {
tempSwapped = false;
for (int j = 0; j < i; j++) {
if (data[j].key > data[j + 1].key) {
// 交换
tempNode = data[j + 1];
data[j + 1] = data[j];
data[j] = tempNode;
tempSwapped = true;
}
}
// 如果此轮未发生交换说明已经为有序
if (!tempSwapped) {
System.out.println("Premature");
break;
}
System.out.println("Round " + (length - i));
System.out.println(this);
}
}
/**
* @Description: 冒泡排序测试
* @Param: []
* @return: void
*/
public static void bubbleSortTest() {
int[] tempUnsortedKeys = { 1, 3, 6, 10, 7, 5, 9 };
String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.bubbleSort();
System.out.println("Result\r\n" + tempDataArray);
}
public static void main(String[] args) {
System.out.println("\r\n-------sequentialSearchTest-------");
sequentialSearchTest();
System.out.println("\r\n-------binarySearchTest-------");
binarySearchTest();
System.out.println("\r\n-------hashSearchTest-------");
hashSearchTest();
System.out.println("\r\n-------insertionSortTest-------");
insertionSortTest();
System.out.println("\r\n-------shellSortTest-------");
shellSortTest();
System.out.println("\r\n-------selectionSortTest-------");
selectionSortTest();
System.out.println("\r\n-------bubbleSortTest-------");
bubbleSortTest();
System.out.println("\r\n-------mergeSortTest-------");
mergeSortTest();
}
运行结果:
-------bubbleSortTest-------
I am a data array with 7 items.
(1,if) (3,then) (6,else) (10,switch) (7,case) (5,for) (9,while)
Round 1
I am a data array with 7 items.
(1,if) (3,then) (6,else) (7,case) (5,for) (9,while) (10,switch)
Round 2
I am a data array with 7 items.
(1,if) (3,then) (6,else) (5,for) (7,case) (9,while) (10,switch)
Round 3
I am a data array with 7 items.
(1,if) (3,then) (5,for) (6,else) (7,case) (9,while) (10,switch)
Premature
Result
I am a data array with 7 items.
(1,if) (3,then) (5,for) (6,else) (7,case) (9,while) (10,switch)