计数排序Java代码实现

结论:由于计数排序不是基于比较的排序,所以时间复杂度可以突破O(nlgn);计数排序时间复杂度为O(n),额外空间复杂度为O(n);

Java实现代码如下:

 1 package com.cmbc.test1;
 2 
 3 public class CountSorting {
 4     
 5     public static void countSort(int[] arr){
 6         if(arr==null||arr.length<2){
 7             return;
 8         }
 9         int max = Integer.MIN_VALUE;
10         for(int i = 0 ;i<arr.length;i++){
11             max = Math.max(max, arr[i]);
12         }
13         int[] help = new int[max+1];
14         
15         for(int i = 0;i<arr.length;i++){
16             help[arr[i]]++;
17         }
18         
19         int i = 0;
20         for (int j = 0; j < help.length; j++) {
21             while (help[j]-- > 0) {
22                 arr[i++] = j;
23             }
24         }
25         
26     }
27     
28     public static void printArray(int[] arr) {
29         if (arr == null) {
30             return;
31         }
32         for (int i = 0; i < arr.length; i++) {
33             System.out.print(arr[i] + " ");
34         }
35         System.out.println();
36     }
37     
38     public static void main(String[] args) {
39         int[] arr = {1,7,3,9,2,0,3,6,9};
40         printArray(arr);
41         countSort(arr);
42         printArray(arr);
43     }
44     
45 
46 }

猜你喜欢

转载自www.cnblogs.com/itqczzz/p/9427915.html