Bucket Sort
import java.util.Arrays; public class BucketSort{ public static void sort(int[] a, int maxVal) { int [] bucket=new int[maxVal+1]; for (int i=0; i<bucket.length; i++) { bucket[i]=0; } for (int i=0; i<a.length; i++) { bucket[a[i]]++; } int outPos=0; for (int i=0; i<bucket.length; i++) { for (int j=0; j<bucket[i]; j++) { a[outPos++]=i; } } } public static void main(String[] args){ int maxVal=5; int [] data= {5,3,2,4,1,5,3,4,3,2,2,1}; System.out.println("Before: " + Arrays.toString(data)); sort(data,maxVal); System.out.println("After: " + Arrays.toString(data)); } } /* Output Before: [5, 3, 2, 4, 1, 5, 3, 4, 3, 2, 2, 1] After: [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5] */
0 comments:
Post a Comment