冒泡排序的基本思想:朝着一个方向比较两两相邻元素的值,若是逆序,则交换两个元素,否则继续比较,若一趟结束后,并没有交换元素,则说明序列已经有序,可以终止比较。
代码
/**
*
*********************
* @Title: bubbleSort
* @Description: TODO(Bubble sort.)
*
*********************
*
*/
public void bubbleSort() {
boolean tempSwapped;
DataNode tempNode;
for (int i = length - 1; i > 0; i--) {
tempSwapped = false;
for (int j = 0; j < i; j++) {
if (data[j].key > data[j + 1].key) {
// Swap.
tempNode = data[j + 1];
data[j + 1] = data[j];
data[j] = tempNode;
tempSwapped = true;
} // Of if
} // Of for j
// No swap in this round. The data are already sorted.
if (!tempSwapped) {
System.out.println("Premature");
break;
} // Of if
System.out.println("Round " + (length - i));
System.out.println(this);
} // Of for i
}// Of bubbleSort
/**
*
*********************
* @Title: bubbleSortTest
* @Description: TODO(Test the method.)
*
*********************
*
*/
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 bubbleSortTst
运行结果:
时间复杂度分析:
最好的情况:待排序序列本身有序,则在第一趟排序后检查更新为false,然后跳出循环,比较次数为
n
−
1
n-1
n−1,移动次数为0,因此时间复杂度为
O
(
n
)
O(n)
O(n);
最坏的情况:待排序序列为逆序,需要
n
−
1
n-1
n−1趟排序,第
i
i
i趟需要进行
n
−
i
n-i
n−i次关键字比较,且每次比较需要交换元素,算下来的时间复杂度为
O
(
n
2
)
O(n^2)
O(n2);
综上,冒泡排序的平均复杂度为
O
(
n
2
)
O(n^2)
O(n2)