JAVA排序之快速排序法(源自张孝祥面试题)

/**
 * 快速排序法
 * @author Shoper
 */
public class QuickSortTest {
 public static void main(String[] args) {
  Integer[] array = new Integer[] { 12, 44, 12, 13, 14, 0, 67, 12, 53 };
  System.out.println("原始数据");
  for (Integer integer : array) {
   System.out.print(integer+",");
  }
  // 数组刚开始,还未排序。传入的的数据为:数组,从哪个位置开始排序,到什么位置结束
  System.out.println("\n排序后");
  new QuickSortTest().sortFactory(array, 0, array.length-1 );
  for (Integer integer : array) {
   System.out.print(integer+",");
  }
 }
 public void sortFactory(Integer[] array, Integer left, Integer right) {
  Integer start = left;
  Integer end = right;
  /*这里是重点(right+left)/2。
   *我之前在这里出错找了很久.middle要取数组中间那个元素才行。之前都写成(array.length+1)/2。
   *错误情况下排序,结果造成了排序对比的元素不正确。
   */
  Integer middle = array[(right + left) / 2];
  Boolean isEnd = false;
  Integer tempDate;
  while (!isEnd) {
   // 找出左边比中间值大的数,如果没有则继续循环
   while (array[start].compareTo(middle) < 0 && start < right) {
    start++; 
   }
   // 找出右边比中间值大的数,如果没有则继续循环
   while (array[end].compareTo(middle) > 0 && end > left) {
    end--; 
   }
   // 将左边大的数和右边小的数进行替换
   if (start <= end) { 
    tempDate= array[start];
    array[start] = array[end];
    array[end] = tempDate;
    start++;
    end--;
   }
   if (!(start <= end)) {
    isEnd = true;
   }
  }
  if (start < right) {
   sortFactory(array, start, right);
  }
  if (end > left) {
   sortFactory(array, left, end);
  }
 }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值