冒泡排序与快速排序--Java
快速排序&冒泡排序
public class MyArray { private int [] array; public MyArray(){ } public MyArray(int [] array){ this.array=array.clone(); } public int[] getArray() { return array; } public void setArray(int[] array) { this.array = array; } //冒泡排序 protected void BubbleSort(){ if(array.length<=0){System.out.println("There is no data");return;} long startTime=System.currentTimeMillis();//计时 for(int i=0;i<array.length-1;i++){ for(int j=0;j<array.length-1-i;j++){ if(array[j]>array[j+1]){//从小到大 int temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } java.text.DecimalFormat df=new java.text.DecimalFormat("#.#######"); System.out.println("Bubble Sort cost time is "+df.format((System.currentTimeMillis()-startTime)/1000.0)+"s"); } //快速排序 protected void QuickSort(){ if(array.length<=0){System.out.println("There is no data");return;} long startTime=System.currentTimeMillis();//计时 _QuickSort(array,0,array.length-1); java.text.DecimalFormat df=new java.text.DecimalFormat("#.#######"); System.out.println("Quick Sort cost time is "+df.format((System.currentTimeMillis()-startTime)/1000.0)+"s"); } private void _QuickSort(int[] list, int low, int high) { // TODO Auto-generated method stub if(low<high){ int middle=getMiddle(list,low,high);//找到中轴线 _QuickSort(list,low,middle-1);//递归对前半采用快速排序 _QuickSort(list,middle+1,high);//递归对后半采用快速排序 } } private int getMiddle(int[] list,int low,int high){//快速排序核心算法 int tmp=list[low];//取第一位作为关键字(比较对象) if(low<high){ while(low<high && list[high]>=tmp){ high--; } list[low]=list[high]; while(low<high && list[low]<=tmp){ low++; } list[high]=list[low]; } list[low]=tmp; return low; } protected void showArray(){ System.out.print("The Array is:"); for(int i=0;i<array.length;i++){ System.out.print(i==(array.length-1)?(array[i]+"\n"):(array[i]+",")); } } }
测试主程序
public class TestMain { public static void main(String[] args){ int [] a={23,12,43,28,80,56,13,43,76,78,54,48,52,93,18,30,25}; // int [] aa={23,12,43,56,13,43,76,78,54,48}; MyArray quickArray=new MyArray(a); quickArray.showArray(); quickArray.QuickSort(); quickArray.showArray(); MyArray bubbleArray=new MyArray(a); bubbleArray.showArray(); bubbleArray.BubbleSort(); bubbleArray.showArray(); } }