I have an assignement that consists of implementing sorting algorithms. Can some
ID: 653625 • Letter: I
Question
I have an assignement that consists of implementing sorting algorithms. Can someone help me with this one?
"public void bucketSort(int[] array, int lowindex, int highindex, boolean reversed)
Your implementation of Bucket Sort should use half as many buckets are there are elements to be sorted. Thus, if highindex - lowindex + 1 == 100, you should use 50 buckets. Assume that the data values are evenly distributed over the range of the list. You will need to do a quick run through the list to find the range of values stored in the list. You need to be able to handle sorting negative as well as positive values. While the list that you are sorting will be ints, you might need to use longs in some places when calculating bucket size. As before, you need to be able to inverse-sort the list. Note that you are sorting ints here and not Comparables -- bucketSort is not a comparison-based sorting algorithm!"
Explanation / Answer
import java.util.*;
public class BucketSort{
public static void bucketSort(int[] array, int lowindex, int highindex, boolean reversed) {
long bucketSize=(highindex-lowindex+1)/2; //calculate size of bucket
int [] bucket=new int[(int) bucketSize]; //declare bucket array
for (int i=0; i<bucket.length; i++) {
bucket[i]=0; //initialize bucket array elements to 0
}
for (int i=0; i<array.length; i++) {
bucket[array[i]]++; //increment the bucket elements depending upon the count of each value in the data array
}
int outPos=0;
for (int i=0; i<bucket.length; i++) {
for (int j=0; j<bucket[i]; j++) {
array[outPos++]=i; //implement bucket sort
}
}
if(reversed==true){ // if asked to reverse the array
int j=array.length-1;
int temp;
for(int i=0;i<array.length/2;i++,j--){
temp=array[i]; //reverse the array elements
array[i]=array[j];
array[j]=temp;
}
}
}
public static void main(String[] args) {
int [] data= {5,1,0,2,4,1,0,5,2,3,1,4}; //initialize array with data
System.out.println("Before: " + Arrays.toString(data)); //print array before bucket sort
bucketSort(data,0, 11, true);//call bucket sort method
System.out.println("After: " + Arrays.toString(data)); //print array after bucket sort
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.