文章图片标题

桶排序 Java 代码

分类:算法与数据结构 作者:阳光倾城 评论:0 点击: 414 次 日期:2016-08-01


桶排序 Java 代码

/* Copyright (c) 2012 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Bucket_sort_(Java)?action=history&offset=20090316075127
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Retrieved from: http://en.literateprograms.org/Bucket_sort_(Java)?oldid=16280
*/
import java.util.Arrays;
public class Bucketsort {
  public static int[] bucketSort(int[] arr) {
    int i, j;
    int[] count = new int[arr.length];
    for(i = 0; i < arr.length; i++ ) {
      count[arr[i]]++;
    }
    for(i=0,j=0; i < count.length; i++) {
      for(; count[i]>0; (count[i])--) {
        arr[j++] = i;
      }
    }
    return arr;
  }
  public static void main(String[] args) {
    int[] arr = new int[] {1,3,4,6,4,2,9,1,2,9};
    for(int i = 0; i < arr.length; i++ ) {
      System.out.print(arr[i] + " ");
    }
    System.out.println();
    arr = bucketSort(arr);
    for(int i = 0; i < arr.length; i++ ) {
      System.out.print(arr[i] + " ");
    }
    System.out.println();
  }
}




声明: 除非注明,本文属( 阳光倾城 )原创,转载请保留链接: http://www.tomrrow.com/archives-7825.html