您的位置:首页 > 其它

第七章 快速排序

2017-01-02 00:00 330 查看
package chap07_Quick_Sort; import static org.junit.Assert.*; import java.util.Arrays; import org.junit.Test; public class SortAlgorithms { /** * 快速排序算法 * * @param n */
static void quickSort(int[] n) { int from = 0; int to = n.length; // quickSort(n, from, to);
quickSort1(n, from, to); } /** * 快速排序的递归实现,将n从start到end之间的数字排序(不包括end) * * @param n * @param start * @param end */
static protected void quickSort(int[] n, int start, int end) { if (start < end - 1) { int a; a = partition(n, start, end); quickSort(n, start, a); quickSort(n, a, end); } } /** * 快速排序的迭代实现 * * @param n * @param start * @param end */
static protected void quickSort1(int[] n, int start, int end) { int a = partition(n, start, end); int b = a; while (start < a - 1) { a = partition(n, start, a); } while (b < end - 1) { b = partition(n, b, end); } } /** * 分割(快速排序中对数组的分割) * * @param n * @param start * @param end * @return
*/
protected static int partition(int[]
3ff0
n, int start, int end) { int p = end - 1; int s = start;// s位于大于a[p]和小于a[p]之间的位置
int tmp; for (int i = start; i < end; i++) { if (n[i] < n[p]) { tmp = n[i]; n[i] = n[s]; n[s] = tmp; s++; } } { tmp = n[s]; n[s] = n[p]; n[p] = tmp; } return s; } @Test public void testName() throws Exception { int[] a = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 }; // System.out.println(Arrays.toString(a)); // partition(a, 0, 12);
quickSort(a); System.out.println(Arrays.toString(a)); } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: