[JAVA]复习各种排序算法--快排

一直在WEB上头忙活,SSH啦,EXT啦,Flex啦,乱七八糟的前端、框架。

近日由于一个机会警醒了作为基础的算法已经差劲到一定地步了~~~

先补了补排序算法,贴点自己的代码上来,都是已经运行过的。看了看时间,排10个数字不到1ms,进入排序方法10次。。。快。。。真快。。。

快排基本思想http://jackey25.iteye.com/blog/456646这位哥们已经说的非常清楚了。。。

public class QuickSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		QuickSort qs = new QuickSort();
		int[] toSort = new int[] { 2, -8, 99, 0, -1, 37, 43, 88, 2, 82 };
		long ss = System.currentTimeMillis();
		toSort = qs.quickSort(toSort, 0, 0, toSort.length - 1);
		println(System.currentTimeMillis() - ss);
		printAll(toSort);
	}

	//int cnt;
	/**
	 * @param toSort
	 * @param standard 作为比较标准数值的位置
	 * @param left 左端起点位置
	 * @param right 右端起点位置
	 */
	private int[] quickSort(int[] toSort,int standard, int left, int right) {
		//print(cnt++ +"| standard: "+standard+",left:"+left+",right:"+right+": ");
		//记住起始结束的位置
		int l = left;
		int r = right;
		//没有相遇,则一直移动
		while(l < r){
			while(r > left && l < r){
				//从右侧找到第一个小于标准数值的,结束右端本次查找
				if(toSort[r] < toSort[standard]){
					swap(toSort,r,standard);
					break;
				}
				r--;
			}
			while(l < right && l < r){
				//从左侧找到第一个大于标准数值的,结束左端本次查找
				if(toSort[l] > toSort[standard]){
					swap(toSort,l,standard);
					break;
				}
				l++;
			}
		}
		//没有小到1个元素1组之前继续分组
		if(l > left){
			quickSort(toSort,left,left,l-1);
		}
		if(r < right){
			quickSort(toSort,r+1,r+1,right);
		}
		return toSort;
	}

	/**
	 * 交换数值
	 */
	private int[] swap(int[] toSort, int i, int j) {
		int temp = toSort[i];
		toSort[i] = toSort[j];
		toSort[j] = temp;
		return toSort;
	}

	private static void printAll(int[] toSort) {
		for (int i = 0; i < toSort.length; i++) {
			System.out.print(toSort[i] + ",");
		}
		System.out.println();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值