- package sort;
- /**
- * 快排代码
- * @author Administrator
- *
- */
- public class Sort {
-
- int [] a = {49,38,65,97,76,13,27,48,78,34,7,4};
- public Sort(){
- quick(a);
- for (int i = 0; i < a.length; i++) {
- System.out.print(a[i]+" ");
- }
-
- }
- /**
- * 使用两个指针low,high,初值分别是数组的头和尾,设置key为第一个记录,首先从high开始向前搜索
- * 第一个小于key的记录和key所在的位置进行交换,然后从low开始向后搜索第一个大于key的记录和此时
- * key所在的位置进行交换,重复至low=high为止,
- * 方法使原数组被key值分为两个整体有序的数组
- * @param list
- * @param low
- * @param high
- * @return
- */
- public int getMiddle(int [] list,int low, int high){
- int temp = list[low];
- while(low<high){
- while(low<high&&list[high]>=temp)
- {
- high--;
- }
- list[low]=list[high];
- while(low<high&&list[low]<=temp)
- {
- low++;
- }
- list[high] = list[low];
- }
- list[low] = temp;
- return low;
- }
- public void _quickSort(int [] list, int low, int high){
- if(low<high){
- int middle = getMiddle(list,low,high);
- _quickSort(list,low,middle-1);//递归调用方法
- _quickSort(list,middle+1,high);
- }
- }
- public void quick(int [] a2){
- if(a2.length>0)
- _quickSort(a2,0,a2.length-1);
- }
-
-
- public static void main(String[] args) {
- new Sort();
- }
- }
复制代码 |
|