现在的位置: 首页 > 综合 > 正文

快速排序算法

2013年02月11日 ⁄ 综合 ⁄ 共 1386字 ⁄ 字号 评论关闭

public static void main(String[] args)
  {
   int[] nums = {27,8,57,9,23,41,65,19,0,1,2,4,5};//声明一维数组并初始化
   System.out.println("该数组的长度为:" + nums.length);
   System.out.println("*************************************************");
   quickSort(nums,0,nums.length-1);//应用快速排序算法
   System.out.println("*************************************************");
   System.out.println("已经走出quickSort方法,并且下面在主程序中显示最后结果");
   for(int i = 0; i < nums.length; i++)//显示排序后的数组
   {
    System.out.print(nums[i] + ",");
   }
  }

  /**快速排序算法*/
  public static void quickSort(int[] a,int low0, int hig0)//实参为quickSort(nums, 0, 12)
  {
   int low=low0;//low0 = 0
   int hig=hig0;//hig0 = 12
  
   if(low >= hig)//条件成立时表示已经排序完毕
    return;
   //transfer是确定指针方向的逻辑变量
   boolean transfer = true;//默认是下标指针从后向前移动
  
   while(low != hig)
   {
    if(a[low] > a[hig])
    {
     //交换数字
     int temp = a[low];
     a[low] = a[hig];
     a[hig] = temp;
     //决定下标移动,还是上标移动
     transfer = (transfer == true) ? false : true;//这里第一次求的transfer为false
    }
    //将指针向前或者后移动
    if(transfer)
    {hig--;}//指针向前移动
    else
    {low++;}//指针向后移动  
    //显示每一次指针移动的数组数字的变化
    for(int i = 0; i < a.length; i++)
    {
     System.out.print(a[i] + ",");
    }
    System.out.print(transfer + ",");
    //此时low = 1, hig = 12
    System.out.println(" (low,hig) =" + "(" + low + "," + hig + ")");         
   }//退出while循环时low == high == 9
  
   //将数组分开两半重新调用quickSort()各自快速排序,确定每个数字的正确位置
   low--;//low == 8
   hig++;// hig == 10
   quickSort(a, low0, low);//quickSort(a, 0, 8)
   quickSort(a, hig, hig0);//quickSort(a, 10,12)     
  }

抱歉!评论已关闭.