package cqupt.zhouchen.exercise; |
import java.util.Random; |
/** |
* 冒泡排序算法练习 |
*/ |
public class Sort { |
|
private int [] array; |
private Random rand; |
|
/** |
* 初始化待排序数据 |
* @param count 待排序数据的个数 |
*/ |
public Sort( int count) { |
array = new int [count]; |
rand = new Random(); |
for ( int i = 0 ; i < array.length; i++) { |
array[i] = rand.nextInt(count); |
} |
} |
|
/** |
* 简单冒泡排序 |
*/ |
public void bubbleSort() { |
int startIndex = array.length - 1 ; |
int temp = 0 ; |
|
for ( int i = 0 ; i < array.length; i++) { |
for ( int j = startIndex; j > i; j--) { |
if (array[j] < array[j - 1 ]) { |
temp = array[j - 1 ]; |
array[j - 1 ] = array[j]; |
array[j] = temp; |
} |
} |
} |
} |
|
/** |
* 优化后的冒泡排序(该算法在数据基本有序的情况下表现不错) |
*/ |
public void bubbleSortBetter() { |
int startIndex = array.length - 1 ; |
int temp = 0 ; |
boolean isSwappable = true ; // 是否交换过数据 |
|
for ( int i = 0 ; i < array.length && isSwappable; i++) { |
isSwappable = false ; // 需要新的一轮比较时,该变量需初始化为FALSE |
for ( int j = startIndex; j > i; j--) { |
if (array[j] < array[j - 1 ]) { |
temp = array[j - 1 ]; |
array[j - 1 ] = array[j]; |
array[j] = temp; |
isSwappable = true ; // 存在数据交换,说明需要继续比较 |
} |
} |
} |
} |
|
/** |
* 打印数据 |
*/ |
public final void print() { |
for ( int i = 0 ; i < array.length; i++) { |
System.out.println(array[i]); |
} |
} |
|
/** |
* 获取待排序的数据个数 |
* @return 待排序数组的长度 |
*/ |
public final int getCount() { |
return array.length; |
} |
public static void main(String[] args) { |
Sort sort = new Sort( 100000 ); // 十万个整数,冒泡排序排一百万个整数时就会很吃力了 |
sort.print(); |
long startTime = System.currentTimeMillis(); |
sort.bubbleSort(); |
sort.bubbleSortBetter(); |
long endTime = System.currentTimeMillis(); |
long time = endTime - startTime; |
sort.print(); |
System.out.println( "排序数据量 == " + sort.getCount()); |
System.out.println( "共耗费时间 == " + time + " ms" ); |
} |
} |