java实现递归快排和非递归快排
2016-05-28 18:23
302 查看
package sort; import java.util.Random; public class QuickSort { public static Random random = new Random(1000); public static void exchange(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static int getPivot(int[] array, int from, int to) { int target = array[to]; int i = from - 1; for (int j = from; j < to; j++) { if (array[j] <= target) { i++; exchange(array, i, j); } } exchange(array, i + 1, to); return i + 1; } public static void insertSort(int[] L, int low, int high) { int i, j, temp; for (i = low + 1; i <= high; i++) { if (L[i] < L[i - 1]) { temp = L[i]; for (j = i - 1; L[j] > temp && j >= low; j--) { L[j + 1] = L[j]; } L[j + 1] = temp; } } } public static void noQuickSort(int[] array, int from, int to) { int stack[] = new int[10000]; int top = 0; int pivot = getPivot(array, from, to); int temp = pivot + 1; for (int i = pivot + 1; i < to + 1; i++) { if (array[i] > array[temp]) { temp = i; } } stack[top++] = to; stack[top++] = pivot; exchange(array, temp, to); for (;;) { if ((pivot - from) > 20) { pivot = getPivot(array, from, pivot - 1); stack[top++] = pivot; } else { insertSort(array, from, pivot - 1); from = pivot + 1; if (top == 1) { break; } pivot = stack[top - 2]; top--; } } } public static void quickSort(int[] array, int from, int to) { if (from < to) { int temp = from + (int) (Math.random() * (to - from)); exchange(array, temp, to); int pivot = getPivot(array, from, to); quickSort(array, from, pivot - 1); quickSort(array, pivot + 1, to); } } }
相关文章推荐
- Spark--用Java开发微服务
- java设计模式-外观模式
- 《单页Web应用--温故JavaScrpt》学习笔记整理
- 利用ant的java任务运行java程序时报错,[java] java.lang.NoClassDefFoundError
- jAVA处理日期(Date)时间(Time)以及相关类的介绍
- java实现VEBTree原型
- java设计模式-装饰模式
- 深入理解Java的接口和抽象类
- 基数排序算法(Java语言)
- Java的反射机制
- java.sql.SQLException: ORA-00911: 无效字符
- java之进制转换
- OC里Self的应用
- struts2下无法用直接通过路径访问.jsp的页面
- javax.servlet.ServletException: Could not resolve view with name 'destination/isOtherExist' in servl
- JavaBean
- springcloud(第九篇)netflix zuul
- springboot设置默认容器为jetty
- Java 小记
- spring+springMVC+Mybatis配置