冒泡排序
1算法原理
1. 冒泡排序算法的运作如下:(从后往前)
2. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
3. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
4. 针对所有的元素重复以上的步骤,除了最后一个。
5. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
2算法分析
时间复杂度
若文件的初始状态是正序的,一趟扫描即可完成排序。所需的关键字比较次数 C和记录移动次数 M 均达到最小值:Cmin= n-1 ,Mmin=0。
所以,冒泡排序最好的时间复杂度为 O(n)。
若初始文件是反序的,需要进行 趟排序。每趟排序要进行
次关键字的比较(1≤i≤n-1),且每次比较都必须移动记录三次来达到交换记录位置。在这种情况下,比较和移动次数均达到最大值:
冒泡排序的最坏时间复杂度为O(n2)。
综上,因此冒泡排序总的平均时间复杂度为 O(n2)。
算法稳定性
冒泡排序就是把小的元素往前调或者把大的元素往后调。比较是相邻的两个元素比较,交换也发生在这两个元素之间。所以,如果两个元素相等,我想你是不会再无聊地把他们俩交换一下的;如果两个相等的元素没有相邻,那么即使通过前面的两两交换把两个相邻起来,这时候也不会交换,所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定排序算法。
Note:参考百度百科 http://baike.baidu.com/view/254413.htm
看代码
public class ArrayStructures {
private int[] theArray = new int[50];
private int arraySize = 10;
public void generateRandomArray(){
for (int i =0; i< arraySize;i++){
theArray[i] = (int)(Math.random()*10 + 10);
}
}
public void printArray(){
StringBuffer sb = new StringBuffer("-");
for (int i = 0; i<arraySize; i++){
sb.append("-----");
}
String septalLine= sb.toString();
System.out.println(septalLine);
for (int i = 0; i<arraySize; i++){
System.out.print("| " + i + " ");
}
System.out.println("|");
System.out.println(septalLine);
for (int i = 0; i<arraySize; i++){
System.out.print("| " + theArray[i] + " ");
}
System.out.println("|");
System.out.println(septalLine);
}
public void bubbleSort(){
for (int i=arraySize-1; i>0; i--){
for(int j=0; j<i; j++)
if(theArray[j]>theArray[j+1]){
swapValues(j,j+1);
}
}
}
public void swapValues(int valueOne, int valueTwo){
int temp = theArray[valueOne];
theArray[valueOne]= theArray[valueTwo];
theArray[valueTwo]=temp;
}
public static void main(String[] args) {
// Generate an Array
System.out.println("Create an array, and fill in random value");
ArrayStructures as = new ArrayStructures();
// Set Random value in Array
as.generateRandomArray();
// Print original array
as.printArray();
System.out.println();
System.out.println("Bubble Sort");
as.bubbleSort();
as.printArray();
System.out.println();
}
}
输出结果
Create an array, and fill in random value
---------------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---------------------------------------------------
| 18 | 15 | 16 | 14 | 11 | 13 | 19 | 14 | 13 | 10 |
---------------------------------------------------
Bubble Sort
---------------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---------------------------------------------------
| 10 | 11 | 13 | 13 | 14 | 14 | 15 | 16 | 18 | 19 |
---------------------------------------------------
转载于:https://blog.51cto.com/10324466/1658785