Groupon面经Prepare: Sort given a range && Summary: Bucket Sort
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Groupon面经Prepare: Sort given a range && Summary: Bucket Sort相关的知识,希望对你有一定的参考价值。
首先是如何sort一个只有0和1的数组,要求inplace. follow up是告诉一个range,如何在O(N)时间内sort好
两个pointer可解
1 package Sorting; 2 import java.util.*; 3 4 public class InplaceSorting { 5 public void sorting(int[] arr) { 6 if (arr==null || arr.length==0) return; 7 int l=0, r=arr.length-1; 8 while (l < r) { 9 while (l<r && arr[l]==0) { 10 l++; 11 } 12 while (l<r && arr[r]==1) { 13 r--; 14 } 15 if (l == r) return; 16 swap(arr, l, r); 17 } 18 } 19 20 public void swap(int[] arr, int l, int r) { 21 int temp = arr[l]; 22 arr[l] = arr[r]; 23 arr[r] = temp; 24 } 25 26 27 /** 28 * @param args 29 */ 30 public static void main(String[] args) { 31 // TODO Auto-generated method stub 32 InplaceSorting sol = new InplaceSorting(); 33 int[] arr = new int[]{0,1,1,0,1,0,0,1}; 34 sol.sorting(arr); 35 System.out.println(Arrays.toString(arr)); 36 } 37 38 }
BucketSort可解
Best case performance: O(n + k), where k is 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 package Sorting; 2 3 import java.util.Arrays; 4 5 public class Solution { 6 public void bucketSort(int[] arr, int min, int max) { 7 int[] bucket = new int[max-min+1]; 8 for (int elem : arr) { 9 bucket[elem-min]++; 10 } 11 int cur = 0; 12 for (int i=0; i<bucket.length; i++) { 13 while (bucket[i] > 0) { 14 arr[cur++] = i+min; 15 bucket[i]--; 16 } 17 } 18 } 19 20 /** 21 * @param args 22 */ 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 Solution sol = new Solution(); 26 int[] arr = new int[]{5,6,9,10,4,11,5,7,6,11}; 27 sol.bucketSort(arr, 4, 11); 28 System.out.println(Arrays.toString(arr)); 29 } 30 31 }
以上是关于Groupon面经Prepare: Sort given a range && Summary: Bucket Sort的主要内容,如果未能解决你的问题,请参考以下文章
Groupon面经:Find paths in a binary tree summing to a target value
G面经Prepare: Print Zigzag Matrix
FB面经 Prepare: Make Parentheses valid
M面经Prepare: Find integer Average of 2 integers.