自从上次写了二分法查找代码后突然打算好好学习一下数据结构.买了一本数据结构与算法......
import java.util.Random;
/**
*
* @author leon.lee
*/
public class BubbleSort {
private int[] arrayData;
public void printArrayList(){
if (arrayData!=null){
for(int i:arrayData){
System.out.print(i+",");
}
System.out.println("");
}
}
private void swap(int x,int y){
int tempV = arrayData[x];
arrayData[x]=arrayData[y];
arrayData[y]=tempV;
}
public void sort(){
/*
* 如果为了效率则把swap方法直接写在代码里,并且不要使用currentValue和nextValue变量
* 如此写法只是为了让结构清晰,方便阅读
*/
for(int i=0;i
for(int j=0;j
int currentValue = arrayData[j];
int nextValue = arrayData[j+1];
if(currentValue>nextValue){
swap(j,j+1);
}
}
}
}
private void initData(){
Random r = new Random(System.currentTimeMillis());
for(int i=0;i
arrayData[i]=r.nextInt(100);
}
}
public BubbleSort(int arraylength){
if(arraylength<1){
throw new ExceptionInInitializerError("您不能使用小于1的数字");
}else if(arraylength>100){
throw new ExceptionInInitializerError("您不能使用大于100的数字");
}
arrayData = new int[arraylength];
initData();
}
public static void main(String[] args) {
BubbleSort bs ;
try{
bs = new BubbleSort(50);
}catch(ExceptionInInitializerError e){
System.out.println(e.getMessage());
return;
}
bs.printArrayList();
bs.sort();
bs.printArrayList();
}
}
run:
6,54,18,6,29,85