冒泡排序也是简单的排序算法之一,算法复杂度为O(n^2),最优情况也是O(n^2)。突然发现自己以前做错了一道题。。。
csdn好像出bug了,不能显示我的全部内容。为了能显示全部内容,我只能一句话一个enter了。
算法简介
冒泡,bubbling。顾名思义就是大的气泡升的高?感觉很难理解。
我觉得冒泡排序还不如叫做沉淀排序。
当我们的试管中有n中不同密度,且互不相容的液体时。
密度越大的沉在越下面。请看下面一段伪代码:
BubbleSort(A)
for i ←1to length[A]
do for j← length[A]
downto i + 1
do if A[j] < A[j-1]
then exchange A[j] ↔ A[j -1]
解释:看了上面的代码,你是否也觉得冒泡排序应该改为沉淀排序?
外层循环一共执行n次。
每次(第i次):把A[i]到A[n](假设数组从1开始)中最小的数,
沉淀到A[i]。
因为无论什么情况,第i次一定会进行n-i次比较,
所以算法的最好情况也是O(n^2)。
代码
package sorting;
public class Data {
/**
* generate an unsorted array of length n
* @param n length
* @param max the maximum integer element of this array
* @return an unsorted array consists of elements range from 1 to max
*/
public static int[] getArray(int n, int max){
int[] result = new int[n];
for(int i =0; i < n; i++){
result[i] = (int)(Math.random() * max + 1);
}
return result;
}
/**
* print the array
* @param arg array
*/
public static void printArray(int[] arg){
StringBuffer temp = new StringBuffer();
for(int i = 0; i < arg.length; i++){
temp.append(arg[i] + "\t");
}
System.out.println(temp);
}
}
package sorting;
public class BubbleSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BubbleSort bs = new BubbleSort();
int[] data = Data.getArray(10, 100);
System.out.print("Source data:\t");
Data.printArray(data);
bs.bubbleSort(data);
System.out.print("Sorted data:\t");
Data.printArray(data);
}
public void bubbleSort(int[] arg){
int j = 0;
int temp = 0;
for(int i = 0; i < arg.length; i++){
j = arg.length - 1;
while(j > i){
if(arg[j] < arg[j - 1]){
temp = arg[j];
arg[j] = arg[j - 1];
arg[j - 1] = temp;
}
j--;
}
}
}
}