快速排序

来源:互联网 发布:阿里云自定义镜像 编辑:程序博客网 时间:2024/05/16 22:12

终于明白快速算法了!

   

 public class QuickSort
{
 public static void main(String[] args)
 {
       int[] num = {11, 4, 53, 2, 6, 75, 3, 5, 9, 10, 43, 22, 11};
       num = sort(num, 0, num.length - 1);
       for(int temp : num)
       {
        System.out.print(temp);
        System.out.print("   ");
       }
 }

 public static int[] sort(int[] date, int low, int top)
 {
  if (low < top)
  {
   int i = low; // sort to right
   int j = top; // sort to left
   int key = date[low]; // 用于比较的数
   while (true)
   {
    while (i < top && date[i] <= key) // 从左边找打比key 大的元素下标
    {
     i++;
    }
    while (j > low && date[j] >= key) // 从右边找到比key小的元素下标
    {
     j--;
    }
    if (i < j)
    {
     swap(date, i, j);
    }
    else
    {
     break;
    }
   }
   swap(date, low, j);  
   sort(date, low, j-1);  // 递归调用
   sort(date, j + 1, top); // 递归

  }
  return date;
 }

 public static void swap(int[] date, int i, int j) // 交换
 {
  int temp = date[i];
  date[i] = date[j];
  date[j] = temp;
 }

}

原创粉丝点击