As an example, consider the following array of 9 integers in the range 1 to 5:
[2, 3, 2, 1, 4, 5, 2, 3, 1]
The count array would contain the following values:
[2, 3, 2, 1, 1]
Working from this set of counts, the sorted array would be:
[1, 1, 2, 2, 2, 3, 3, 4, 5]
Bucket sort has the unfortunate property of destroying (and recreating) the original data set, which is why it can only be used for integer values. However, it is very fast when you only need to sort integers.
Write a small Java program that does the following:
1. Prompts the user to enter a positive integer n. Your program will sort a list of integers in the range 1-n.
2. Randomly generates a list of 100 integers in the specified range (Use the Random class to do this -- an example will be provided shortly on Blackboard).
3. Prints the unsorted list to the screen.
4. Uses bucket sort to sort the data set. Write a separate bucketSort() method to do the sorting and return a sorted version of the data set; don't do the sorting directly in main()!
5. Prints the sorted data set to the screen.
import java.util.Arrays;
import java.util.Scanner;
public class Bucketsort {
public static int[] bucketSort(int[] arr) {
int i, j;
int[] count = new int[arr.length];
Arrays.fill(count, 0);
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) {
//System.out.println(" Input an integer ");
//Scanner sc = new Scanner(System.in);
//Random r = new Random();
int[] arr = new int[] {2, 3, 2, 1, 4, 5, 2, 3, 1};
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();
}
}
//output: 112223345
I had a few problem writing this code so instead I wrote it with the given example in it
I know that I have to use System.out.println("enter a integer ") ...an Scanner... and random class but I cant seem to put all these together I think theres something wrong with the counter. HElp
thanks.