首页 > 代码库 > BucketSort

BucketSort

code 1:

 1 public static void bucketSort(int[] array) { 2     int len = array.length; 3     int min = array[0], max = array[0]; 4     // 找出最小值、最大值 5     for (int i : array) { 6         if (i < min) 7             min = i; 8         if (i > max) 9             max = i;10     }11     //12     int[] tmp = array.clone();13     // 生成n个桶14     int[] buckets = new int[max - min + 1];15     for (int i : array)16         buckets[i - min]++;17     for (int i = 1; i < buckets.length; i++)18         buckets[i] += buckets[i - 1];19     for (int i = len - 1; i >= 0; i--)20         array[--buckets[tmp[i] - min]] = tmp[i];21 //    for (int i = 0; i < len; i++)22 //        array[--buckets[tmp[i] - min]] = tmp[i];23 }

 

code 2:

 1 public static void bucketSort(int[] array) { 2     int min = array[0]; 3     int max = array[0]; 4     for (int tmp : array) { 5         if (tmp < min) 6             min = tmp; 7         if (tmp > max) 8             max = tmp; 9     }10     int[] buckets = new int[max - min + 1];11     for (int v : array)12         buckets[v - min]++;13     int k = 0;14     for (int i = 0; i < buckets.length; i++)15         for (int j = 0; j < buckets[i]; j++)16             array[k++] = i + min;17 }

 

BucketSort