演算法-面試題2萬多名員工按年齡排序
阿新 • • 發佈:2018-12-25
2萬多名員工按年齡排序演算法,
演算法思想是選擇排序演算法的思想,同時考慮到2萬多員工,在某個年齡取值時會有多位員工的實際情況。
思路
第一遍搜尋找出,最小年齡為m個minAge, 最大年齡為n個maxAge,這樣得到年齡的取值區間[minAge, maxAge]; 第二遍,搜尋步進1,全部找出後,放到m個minAge後,依次。。。
C#程式碼實現,
人員模型為,
public class Person
{
public Person(int staffno, int age)
{
this.staffno = staffno;
this.age = age;
}
//工號
public int staffno {get;set;}
//年齡
public int age{get;set;}
}
步進為1的排序搜尋演算法:
static void sort()
{
if (list == null) return;
//找出人員年齡最小的list
List<Person> minAgePersons = GetAgePersons(list.Min(per => per.age));
//找出人員年齡最大的list
List<Person> maxAgePersons = GetAgePersons(list.Max(per => per.age));
//去掉這些最值
list = list.Except(minAgePersons).Except(maxAgePersons).ToList();
for(int age = minAgePersons[0].age+1;age<maxAgePersons[0].age;age++)
{
List <Person> agePersons = GetAgePersons(age);
minAgePersons.AddRange(agePersons);
list.Except(agePersons);
}
minAgePersons.AddRange(maxAgePersons);
list = minAgePersons;
}
static List<Person> GetAgePersons(int age)
{
return list.FindAll(person => person.age == age);
}
人員年齡不一定步進為1,所以改進sort()之,
static void sort()
{
if (list == null) return;
//找出人員年齡最小的list
List<Person> minAgePersons = GetAgePersons(list.Min(per => per.age));
list = list.Except(minAgePersons).ToList();
do
{
List<Person> tmpminAgePersons = GetAgePersons(list.Min(per => per.age));
minAgePersons.AddRange(tmpminAgePersons);
list = list.Except(tmpminAgePersons).ToList();
} while (list.Count > 0);
list = minAgePersons;
}
原始碼地址:
下載後,list = list.Except(minAgePersons).ToList()移動到do迴圈外。(上傳程式碼後才發現的一個小問題)
http://download.csdn.net/detail/daigualu/9782742