快速排序
package leetcode.sort; import java.util.Arrays; /** * QuickSort * Created by blank on 2015-09-22 下午12:06. */ public class QuickSort { static int[] arr = new int[20]; public static void main(String[] args) { for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * 200); } System.out.println(Arrays.toString(arr)); quickSort(0, arr.length - 1); System.out.println(Arrays.toString(arr)); } private static void quickSort(int left, int right) { if (right - left < 1) return; swap(left, randint(left, right));//选取数组中随机一个元素作为划分元素 int tmp = arr[left]; int i = left; int j = right + 1; while (true) { do i++; while (i <= right && arr[i] < tmp);//从左侧开始遍历,直到找到一个大于等于tmp的或者到达最右侧 do j--; while (arr[j] > tmp);//从右侧开始遍历,找到一个小于等于tmp的 if (i > j)//当交叉时 break break; swap(i, j);//不交叉则将左侧比tmp大的与右侧比tmp小的交换 } swap(left, j);//循环终止时,交换a[left]和a[j] quickSort(left, j - 1);//对左侧递归调用quickSort quickSort(j + 1, right);//对右侧递归调用quickSort } private static void swap(int x, int y) { int tmp = arr[x]; arr[x] = arr[y]; arr[y] = tmp; } private static int randint(int a, int b) { //产生a与b之间的随机数 return a + (int) (Math.random() * 100) % (b - a + 1); } }