快速排序算法bug修正

原作者:http://blog.csdn.net/u013144863/article/details/53236230#java

原本想在下面评论的,但是代码过长,只好重新写一篇博客。


import java.util.Random;

/**
 * 
 * 
 * @author wangqingxin
 * 
 */
public class QuickSort {
	public static void main(String[] args) {
		Random ran = new Random();
		//int[] sort = { 34, 38, 49, 32, 7, 41, 42, 8, 34, 24 };
			int[] sort=new int[10];
		 for (int i = 0; i < 10; i++) {
		 sort[i] = ran.nextInt(50);
		 }
			System.out.print("排序前的数组为");
		for (int i : sort) {
			System.out.print(i + " ");
		}

		//quickSort_wqx(sort, 0, sort.length - 1);
		quickSort(sort, 0, sort.length - 1);
		System.out.println("");
		System.out.print("排序后的数组为");
		for (int i : sort) {
			System.out.print(i + " ");
		}
	}


	
	/**
	 * 快速排序
	 * 
	 * 最优解
	 */
	  public static void quickSort(int[] a, int low, int high) {
	      //递归快速排序
	      int pivotLoc = 0;//中心点
	      if (low < high) {
	          pivotLoc = partitionLoc(a, low, high);
	          quickSort(a, low, pivotLoc-1);
	          quickSort(a, pivotLoc+1, high);
	      }
	  }

	  //获取到a的下标 low ~ high 中, a[low]的应该放的位置, 即左边的数 < a[low] 右边的数 > a[low]
	  private static int partitionLoc(int[] a, int low, int high) {
	    //  a[0] = a[low];
		  int key = a[low];
	      while (low < high) {
	          while (low < high && a[high] >= key) {
	              high--;
	          }
	          a[low] = a[high];
	          while (low < high && a[low] <= key) {
	              low++;
	          }
	          a[high] = a[low];
	      }
	      a[low] = key;
	      return low;
	  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值