快速排序
此排序包括升序和降序
升序为例,从low(低位)到hight(高位),拿第一个作为基准值(benchmark)作比较,先从高位向低位找一个比基准值小的数(第j位),再从低位向高位找一个比基准值大的数(第i位),交换这两个数,就是数小的移向左边,数大的移向右边,直到i位和j位相等,把基准数插入该位置,然后递归low,i-1和i+1,hight,直到低位和高位相等。
package com.bsc.algorithm.sort.quick; import com.bsc.algorithm.sort.inf.AbstractSort; public class QuickSort<T extends Comparable<T>> extends AbstractSort<T> { private void sort(T[] data, int low, int hight, int cr) { if (low >= hight) { return; } int i = low; int j = hight; //基准值 T benchmark = data[low]; do { // cr == 1(升序)时,从高位向低位找一个数比benchmark小的 while (i < j && compare(benchmark, data[j]) != cr) { j--; } // cr == 1时(升序),从低位向高位找一个数比benchmark大的 while (i < j && compare(data[i], benchmark) != cr) { i++; } if (i < j) { //找到后交换两数,然后继续找 swap(data, i, j); }else{ //找不到就结束 //此时i == j,data[i]和左边的数都比benchmark小,右边的数都比benchmark大 break; } } while (true); data[low] = data[i]; data[i] = benchmark; sort(data, low, i - 1, cr); sort(data, i + 1, hight, cr); } @Override protected void sort(T[] data, int cr) { sort(data, 0, data.length - 1, cr); } }
测试
ArrayGenerator请参考数组数据生成器
package com.bsc.algorithm.sort.test; import java.util.Arrays; import com.bsc.algorithm.data.generator.ArrayGenerator; import com.bsc.algorithm.sort.inf.ISort; import com.bsc.algorithm.sort.quick.QuickSort; public class SortTest { public static void main(String[] args) { ISort<Integer> sortInt = new QuickSort<Integer>(); Integer[] dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99); System.out.println("原序:" + Arrays.toString(dataInt)); sortInt.sortAsc(dataInt); System.out.println("升序:" + Arrays.toString(dataInt) + "\n"); dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99); System.out.println("原序:" + Arrays.toString(dataInt)); sortInt.sortDesc(dataInt); System.out.println("降序:" + Arrays.toString(dataInt) + "\n"); ISort<Character> sortChar = new QuickSort<Character>(); Character[] dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90); System.out.println("原序:" + Arrays.toString(dataChar)); sortChar.sortAsc(dataChar); System.out.println("升序:" + Arrays.toString(dataChar) + "\n"); dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90); System.out.println("原序:" + Arrays.toString(dataChar)); sortChar.sortDesc(dataChar); System.out.println("降序:" + Arrays.toString(dataChar) + "\n"); } }