若是在面试中有面试官要求你写一个O(n)时间复杂度的排序算法,你千万不要马上说:这不可能!虽然前面基于比较的排序的下限是O(nlogn)。可是确实也有线性时间复杂度的排序,只不过有前提条件,就是待排序的数要知足必定的范围的整数,并且计数排序须要比较多的辅助空间。其基本思想是,用待排序的数做为计数数组的下标,统计每一个数字的个数。而后依次输出便可获得有序序列。 面试
实现代码:
public class CountSort { public static void countSort(int[] arr) { if(arr == null || arr.length == 0) return ; int max = max(arr); int[] count = new int[max+1]; Arrays.fill(count, 0); for(int i=0; i) { count[arr[i]] ++; } int k = 0; for(int i=0; i) { for(int j=0; j) { arr[k++] = i; } } } public static int max(int[] arr) { int max = Integer.MIN_VALUE; for(int ele : arr) { if(ele > max) max = ele; } return max; } }