6.快速排序

1.快速排序简介

 

 2.原理

 

 3.图解排序过程

 

 

  4.代码实现

 1 import java.util.*;
 2 import java.io.*;
 3 
 4 public class Quick {
 5 
 6     public static void main(String[] args)throws Exception {
 7         // Integer[] a = {10,9,8,7,6,5,4,3,2,1,0,0,-1};
 8         // 读取文件中的逆序数组,个人测试数据为10万
 9         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("arr.txt"))));
10         LinkedList<Integer> list = new LinkedList<>();
11         String line = "";
12         while((line = br.readLine()) != null ) {
13             list.add(Integer.parseInt(line));
14         }
15         Integer[] arr = asArray(list);
16         long start = System.currentTimeMillis();
17         sort(arr,0,arr.length-1);
18         long end = System.currentTimeMillis();
19         System.out.println("用时"+(end-start)+"毫秒");
20         System.out.println(Arrays.toString(arr));
21     }
22     
23     private static int partition(Integer[] arr, int low,int high) {
24         // 对判断基准的取值使用随机数,避免碰到逆序数组的时候,时间复杂度退化成O(n^2),而且这种情况还很容易导致栈溢出
25         Random random = new Random();
26         int index = low + random.nextInt(high - low);
27         swap(arr,low,index);
28         int mark = arr[low];
29         int right = low;
30         int left = high;
31         
32         while(true) {
33             while(arr[right] <= mark) {
34                 if(right == high)
35                     break;
36                 right++;
37             }
38             
39             while(arr[left] > mark) {
40                 if(left == low)
41                     break;
42                 left--;
43             }
44             
45             if(right >= left) {
46                 Integer temp = arr[left];
47                 arr[left] = mark;
48                 arr[low] = temp;
49                 break;
50             } else {
51                 Integer temp = arr[right];
52                 arr[right] = arr[left];
53                 arr[left] = temp;
54             }
55         }
56         return left;
57     }
58     
59     private static void sort(Integer[] arr,int low,int high) {
60         if(low >= high)
61             return;
62         int mid = partition(arr,low,high);
63         sort(arr,low,mid-1);
64         sort(arr,mid+1,high);
65     }
66     
67     private static Integer[] asArray(List<Integer> list) {
68         Integer[] arr = new Integer[list.size()];
69         for(int i = 0 ; i < list.size();i++)
70             arr[i] = list.get(i);
71         return arr;    
72     }
73     
74     public static void swap(Comparable[] arr, int i, int j) {
75         Comparable temp = arr[i];
76         arr[i] = arr[j];
77         arr[j] = temp;
78     }
79 }

5.测试结果

 

 

posted on 2020-10-18 16:13  nameless_vi  阅读(90)  评论(0编辑  收藏  举报

导航