桶排序
前言
原理后续补全
正文
public static double[] bucketSort(double[] array)
{
double max = array[0];
double min = array[0];
for (var i = 1; i < array.Length; i++)
{
if (array[i] > max)
{
max = array[i];
}
if (array[i] < min)
{
min = array[i];
}
}
var rang = max - min;
// 桶的数量
var bucketNum = array.Length;
// 生成桶
ArrayList bucketList= new ArrayList();
for (int i = 0; i < bucketNum; i++)
{
bucketList.Add(new List<double>());
}
for (int i = 0; i < array.Length; i++)
{
int index=(int)((array[i] - min) / (rang / (bucketNum - 1)));
List<double> current= (List<double>)(bucketList[index]);
current.Add(array[i]);
}
for (int i = 0; i < bucketList.Count; i++)
{
//对进行排序
var current=(List<double>)(bucketList[i]);
current.Sort();
}
double[] sortArray = new double[array.Length];
var sortArrayIndex = 0;
foreach (var list in bucketList)
{
foreach (var data in (List<double>)list)
{
sortArray[sortArrayIndex] = data;
sortArrayIndex++;
}
}
return sortArray;
}