简体   繁体   English

具有最大值和最小值的桶排序

[英]Bucket Sort with a max and min value

For an assignment, I have to create a method that implements bucket sort on a array of size 25 that is filled with random integers between 0 and 25 (inclusive) and I have to use the use the max value as a parameter for the method.对于分配,我必须创建一个方法,该方法在大小为 25 的数组上实现桶排序,该数组填充了 0 到 25(含)之间的随机整数,并且我必须使用最大值作为该方法的参数。 Max is the largest element in the array(in my code its 25). Max 是数组中最大的元素(在我的代码中是 25)。 Then I have to create another method that implements bucket sort on the same array but now its filled with random integers between -25 and 25 (inclusive) but in this method I have to use a max value and a min value which are both passed in. The max value is the same but min is the smallest value in the array(in my code its -25).然后我必须创建另一个在同一个数组上实现桶排序的方法,但现在它填充了 -25 和 25(含)之间的随机整数,但在这个方法中我必须使用最大值和最小值,它们都传入. 最大值相同但最小值是数组中的最小值(在我的代码中为 -25)。 I completed the first part but I am having trouble figuring out how to change my first method to complete the second part.我完成了第一部分,但我无法弄清楚如何更改我的第一种方法来完成第二部分。 Here is my first method:这是我的第一种方法:

public static void sort( int[] arr, int max )
{
  int min = 0;
  int [] bucket=new int[max+1];
  for (int i=0; i< max; i++) {
    bucket[arr[i]]++;;
  }
  for (int i=0; i<bucket.length; i++) {
    for (int j=0; j<bucket[i]; j++) {
       arr[min++]=i;
    }
  }
}

You just have to create buckets to hold values from min to max.您只需要创建存储桶来保存从最小值到最大值的值。 For ex if min is -25 and max is 25, then you have to create 51 buckets.例如,如果 min 为 -25,max 为 25,则您必须创建 51 个存储桶。 If min is -4 and max is 25 then you have to create 30 buckets.如果 min 为 -4,max 为 25,则您必须创建 30 个存储桶。 So I would change your code to generate the buckets and also a little bit of the inner logic to populate the buckets.因此,我会更改您的代码以生成存储桶以及一些用于填充存储桶的内部逻辑。 Here is how you can do it :您可以这样做:

public static void sort( int[] arr, int min, int max )
{
  int nBuckets = max - min + 1;
  int [] bucket=new int[nBuckets];
  for (int i=0; i< arr.length; i++) {
       bucket[arr[i] - min]++;

  }
  int index = 0;
  for (int i=0; i<bucket.length; i++) {
      for (int j =0; j<bucket[i]; j++) {
          arr[index++]=min;
      }
      min++;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM