private void BucketSort(int[] values)
{
    //make sure we have values to wort
    if (values == null || values.Length == 0) return;

    //variables to hold the min and max values of the
    //array, set them both to the first value in our array
    //so they're initialized
    int max = values[0];
    int min = values[0];

    //here we will loop through the array, starting at the first index (1)
    for (int i = 1; i < values.Length; i++)
    {
        //inside the loop we will find the max value in the array
        if (values[i] > max)
max = values[i];
        //inside the loop we will find the min value in the array
        if (values[i] < min)
min = values[i];
    }

    //create a bucket for holding the values in the array. Each
    //value will be stored in it's values's index
    //EXAMPLE: 15 will be at index 15 minus the min value
    List<int>[] holder = new List<int>[max - min + 1];

    //now inistialize our holder variable by creating a
    //new List<int>() for each value in our holder
    for (int i = 0; i < holder.Length; i++)
    {
        holder[i] = new List<int>();
    }

    //start moving values to our holder object
    for (int i = 0; i < values.Length; i++)
    {
        holder[values[i] - min].Add(values[i]);
    }
 
    //variable to hold the index of the
    //original array
    int k = 0;

    //now we move the items from pour temporary holder back to the array
    //in the new sorted order
    for (int i = 0; i < holder.Length; i++)
    {
        if (holder[i].Count > 0)
        {
            for (int j = 0; j < holder[i].Count; j++)
            {
                values[k] = holder[i][j];
                k++;
            }
        }
    }
}

Post a Comment

 
Top