最近有一个项目上的需求,在一个无序的数组中找到最中间值的那个元素,关键是数组的长度很长, 经过测试,如果采用传统的冒泡排序算法,100万数组需要耗时几万毫秒,后采用下面的定向组数算法,不去排序,而是记录每个元素出现的次数,最后找到中间值,这样下来,100数组需要的耗时为6毫秒,效率提高了几万倍!
private int GetCenterItem(int[] array)
{
int result = 0;
int max = 0;
//先求出源数组中最大的值
for(int i = 0; i < array.Lenght; i++)
{
if(max < array[i]) max = array[i];
}
//根据最大值创建一个新的标记数组,用来统计每个元素出现的次数
int[] flag = new int[max + 1];
for(int i = 0; i < array.Length; i++)
{
flag[array[i]]++;
}
//遍历这个flag数组,当次数累加和大于等于源数组长度一半时,此于的下标i就是源数组的中间值
int sum = 0;
int center = array.Lenght / 2;
for(int i = 0;i < flag.Length; i++)
{
sum += flag[i];
if(sum >= center)
{
result = i;
break;
}
}
return result;
}
2022.6.9 记录于此