sohaib majeed
sohaib majeed

Reputation: 13

Bucket sort in C# - how to?

static void Main(string[] args)
{
    double[] array = { 0.37, 0.25, 0.86, 0.23, 0.09, 0.21, 0.17, 0.71 };
    double[] sortedArray =BucketSort(array);

    // PrintResult(sortedArray);
}

public double[] BucketSort(double[] array)
{
    List<List<double>> buckets = new List<List<double>>();
    InitializeBuckets(buckets);

    Scatter(array, buckets);

    int i = 0;
    foreach (List<double> bucket in buckets)
    {
        double[] arr = bucket.ToArray();
        InsertionSort(arr);

        foreach (double d in arr)
        {
            array[i++] = d;
        }
    }

    return array;
}

private void Scatter(double[] array, List<List<double>> buckets)
{
    foreach (double value in array)
    {
        int bucketNumber = GetBucketNumber(value);
        buckets[bucketNumber].Add(value);
    }
}

private void InsertionSort(double[] array)
{
    int j;
    double temp;

    for (int i = 1; i < array.Length; i++)
    {
        j = i;
        while (j > 0 && array[j] < array[j - 1])
        {
            temp = array[j];
            array[j] = array[j - 1];
            array[j - 1] = temp;
            j--;
        }
    }
}

private int GetBucketNumber(double value)
{
    double val = value * 10;
    int bucketNumber = (int)Math.Floor(val);
    return bucketNumber;
}

private static void InitializeBuckets(List<List<double>> buckets)
{
    for (int i = 0; i < 10; i++)
    {
        List<double> a  = new List<double>();
        buckets.Add(a);
    }
}

I get an error

An Object reference is required for the non static field, method or property

Can anyone solve this problem and explain it?

Upvotes: 1

Views: 5084

Answers (2)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

The Main method is a static method, which means you can call it without an object instance. The rest of the methods are instance methods, so you need an instance of the class in which they are declared in order to call them.

If a method is not accessing non-static fields and methods from the class you can make it static to make its use more flexible. So in your code, if you make all methods static, the error will go away.

public static double[] BucketSort(double[] array)
{
    ...
}

Alternatively you can create an instance of your object and call it that way. ?Assuming the containing class is Program and it has a default constructor, your code will be:

  var program = new Program();
  double[] sortedArray = program.BucketSort(array);

Upvotes: 3

Han
Han

Reputation: 3072

Add the static keyword to your methods. Change these methods:

  • BucketSort
  • Scatter
  • InsertionSort
  • GetBucketNumber

Example:

public static double[] BucketSort(double[] array)

Upvotes: 1

Related Questions