1.冒泡法排序
运行思想就是每一次后当前元素和后一个元素相比,如果大于后面的元素,则交换位置,以此循环,每次可以确定一个元素的最终位置。最坏的时间复杂度为O(n²),这种排序方法只适合于数据量较小的时候,效率也较为低下。
2.代码
因为之前自己用C写过冒泡排序的代码,也还有些记忆,就先自己尝试着写了下
public void bubbleSort1() {
DataNode tempNode;
for (int c = 0; c < length; c++) {
for (int i = 0; i < length -1 - c; i++) {
if (data[i].key > data[i + 1].key) {
tempNode = data[i + 1];
data[i + 1] = data[i];
data[i] = tempNode;
}
}
System.out.println("Round" + (c+1));
System.out.println(this);
}
}
当然也可以正常出结果。
接下来就是老师之前写的代码,增加了一个tempSwapped来判断是否已经“早熟”,这样就不会像上面的那样,已经排序完毕后仍在循环中运行,浪费时间。
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;
} // Of if
} // Of for j
if (!tempSwapped) {
System.out.println("Premature");
break;
} // Of if
System.out.println("Round" + (length - i));
System.out.println(this);
} // Of for i
}// of bubblesort
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);
}// Of bubbleSortTest
增加判断早熟过后,可以有效简短代码的运行次数和时间。
3.总结
当我们可以实现一个算法时,就应该有意识去想能不能进一步的优化,就像这冒泡排序一样。