// TestBucketSort.java ปรับปรุง : 2548-06-05 () // เคล็ด : นำค่าของอาร์เรย์ในชุดหนึ่ง ไปนับตาม index ของอาร์เรย์อีกชุด และพิมพ์อาเรย์ชุดหลัง // โปรแกรมสำหรับ จัดเรียงข้อมูล แบบ Bucket // แหล่งอ้างอิง // http://www.thaiall.com/class // http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html // http://www.java2s.com/ExampleCode/Collections-Data-Structure/Sort-Search.htm // class TestBucketSort { private int size; private int[] count; TestBucketSort(int size) { this.size = size; count = new int[size]; } public int getSize() { return size; } public void sort(int[] array) { for(int i = 0; i < size; i++) count[array[i]]++; for(int i = 0, j = 0; i < size; i++) while(count[i] > 0) { array[j++] = i; count[i]--; } } public void show(int[] arr) { for(int i = 0; i < arr.length; i++) { if(arr[i] > 0) { System.out.print("\t" + arr[i]); if(i % 9 == 0) System.out.println(); } } } public static void main(String[] args) { TestBucketSort bks = new TestBucketSort(100); int list[] = new int[bks.getSize()]; // for(int i = 0; i < bks.getSize(); i++) { // list[i] = (int)(Math.random() * 100); // } list[0] = 51; list[1] = 46; list[2] = 14; list[3] = 35; list[4] = 22; bks.sort(list); bks.show(list); } }