The first is how to sort a array of only 0 and 1, which requires inplace. Follow up is to tell a range how to sort well within O (N) time
Two X-pointer can be solved
1 Packagesorting;2 ImportJava.util.*;3 4 Public classinplacesorting {5 Public voidSorting (int[] arr) {6 if(arr==NULL|| arr.length==0)return;7 intL=0, R=arr.length-1;8 while(L <r) {9 while(L<r && arr[l]==0) {Tenl++; One } A while(L<r && Arr[r]==1) { -r--; - } the if(L = = r)return; - swap (arr, L, R); - } - } + - Public voidSwapint[] arr,intLintr) { + inttemp =Arr[l]; AARR[L] =Arr[r]; atARR[R] =temp; - } - - - /** - * @paramargs in */ - Public Static voidMain (string[] args) { to //TODO auto-generated Method Stub +Inplacesorting Sol =Newinplacesorting (); - int[] arr =New int[]{0,1,1,0,1,0,0,1}; the sol.sorting (arr); * System.out.println (arrays.tostring (arr)); $ }Panax Notoginseng -}
Bucketsort can be solved
Best Case Performance:o (n + k), where K was the size of buckets or the range between Min and Max in original array
Worst case performance:o (n^2)
Aver case Performance:o (n + k)
Worst case space:o (N*k)
Bucketsort works as follows:
1. Set up an array of initially empty buckets (should know the range)
2. Go over the original array, put each object in its bucket
3. Sort each non-empty bucket.
4. Visit the buckets in order and put all elements back into the original array.
1 Packagesorting;2 3 Importjava.util.Arrays;4 5 Public classSolution {6 Public voidBucketsort (int[] arr,intMinintmax) {7 int[] Bucket =New int[Max-min+1];8 for(intElem:arr) {9bucket[elem-min]++;Ten } One intCur = 0; A for(inti=0; i<bucket.length; i++) { - while(Bucket[i] > 0) { -arr[cur++] = i+min; thebucket[i]--; - } - } - } + - /** + * @paramargs A */ at Public Static voidMain (string[] args) { - //TODO auto-generated Method Stub -Solution Sol =Newsolution (); - int[] arr =New int[]{5,6,9,10,4,11,5,7,6,11}; -Sol.bucketsort (arr, 4, 11); - System.out.println (arrays.tostring (arr)); in } - to}
Groupon noodles by Prepare:sort given a range && Summary:bucket Sort