写个快速排序和冒泡排序的例子,比较下2者
这个快速排序写的不是特别好,凑合一下吧,呵呵
这个快速排序写的不是特别好,凑合一下吧,呵呵
- package sort;
- public class QuickSort
- {
- /**
- * @author yjb87
- * @分析 快速排序法 和 冒泡排序法 的详细步骤
- * @结论 快速排序法 在多核CPU下具有更高的效率
- */
- public static void main(String[] args)
- {
- int array[] = new int[10];
- array[0] = 13;
- array[1] = 6;
- array[2] = 2;
- array[3] = 10;
- array[4] = 5;
- array[5] = 4;
- array[6] = 1;
- array[7] = 7;
- array[8] = 3;
- array[9] = 9;
- int array1[] = array.clone();
- System.out.println("*******************使用快速排序法********************");
- print(array);
- quickSort(array,0,9,0,1);
- System.out.println("*******************使用冒泡排序法********************");
- print(array1);
- bubble(array1,0);
- }
- /***快速排序法***/
- public static void quickSort(int array[],int first,int last,int count,int realNum)
- {
- /**
- * @array 需要排序的数组
- * @first 初始值为数组第一个元素的索引,即0
- * @last 初始值为数组的最后一个元素的索引,即数组长度
- * @count 计算排序步数
- * @realNum 分治成多少部分进行排序
- * */
- int temp,low,high,list_separator;
- low = first;
- high = last;
- list_separator = array[(first+last)/2];
- do
- {
- while(array[low] < list_separator)
- {
- low++;
- }
- while(array[high] > list_separator)
- {
- high--;
- }
- if(low<=high)
- {
- count++;
- //System.out.println("第 "+count+" 步 同时分 "+realNum+" 个部分进行排序 /n");
- System.out.println("第 "+count+" 步");
- temp=array[low];
- array[low++]=array[high];
- array[high--]=temp;
- print(array);
- }
- }while(low <= high);
- if(first<high)
- {
- realNum++;
- quickSort(array,first,high,count,realNum);
- }
- if(low<last)
- {
- realNum++;
- quickSort(array,low,last,count,realNum);
- }
- }
- /**冒泡排序法**/
- public static void bubble(int array[],int count)
- {
- /**
- * @array 需要排序的数组
- * @count 计算排序步数
- * */
- int temp;
- for(int i=0;i<array.length;i++)
- {
- for(int j=i+1;j<array.length;j++)
- {
- if(array[i]>array[j])
- {
- temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- count++;
- System.out.println("第 "+count+" 步");
- print(array);
- }
- }
- }
- }
- public static void print(int array[])
- {
- for(int i=0;i<array.length;i++)
- {
- if(array[i]<10)
- System.out.print(" - "+array[i]);
- else
- System.out.print(" - "+array[i]);
- }
- System.out.println();
- }
- }