Java 快速排序

public class QuickSortJava {
	public static void main(String[] args) {
		int[] aa = { 0, 49, 38, 65, 97, 76, 13, 27 };

		new QuickSort().quickSort(aa, 0, 7);

		for (int result : aa) {
			System.out.println(result);
		}
	}
}

class QuickSort {
	private int partition(int[] L, int low, int high) {

		L[0] = L[low];
		int pivotkey = L[low];
		while (low < high) {
			while (low < high && L[high] >= pivotkey) {
				high--;
			}
			L[low] = L[high];
			while (low < high && L[low] <= pivotkey) {
				low++;
			}
			L[high] = L[low];
		}
		L[low] = L[0];
		return low;
	}

	public void quickSort(int[] L, int low, int high) {
		if (low < high) {
			Integer pivotloc = partition(L, low, high);
			quickSort(L, low, pivotloc - 1);
			quickSort(L, pivotloc + 1, high);
		}
	}

}


下面这种方法简单粗暴

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QuickSortB {
	public static void main(String[] args) {
		Integer[] list = { 49, 38, 65, 97, 76, 13, 27 };
		List<Integer> items = new ArrayList<Integer>();

		for (Integer x : list) {
			items.add(x);
		}

		QuickSortBB qb = new QuickSortBB();
		qb.sort(items);

		for (Integer x : items) {
			System.out.println(x);
		}

	}
}

class QuickSortBB {
	public void sort(List<Integer> items) {
		if (items.size() > 1) {
			List<Integer> smaller = new ArrayList<>();
			List<Integer> same = new ArrayList<>();
			List<Integer> larger = new ArrayList<>();

			Integer chosenItem = items.get(items.size() / 2);

			for (Integer i : items) {
				if (i < chosenItem) {
					smaller.add(i);
				} else if (i > chosenItem) {
					larger.add(i);
				} else {
					same.add(i);
				}
			}

			sort(smaller);
			sort(larger);

			items.clear();
			items.addAll(smaller);
			items.addAll(same);
			items.addAll(larger);

		}
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值