Interviewer: Please implement a sorting algorithm that requires time complexity of O (N)
Interviewer: We want to sort all employees of the company by age, our company has a total of tens of thousands of employees;
Interviewer: Only use a constant size auxiliary space , Must not exceed O (N);
Method 1: Create a class to implement the student's name, age, gender attributes, and can be sorted according to a certain attribute. You can also use a dictionary, but it does n’t seem to be intuitive, so I wo n’t write it for now. Using bubble sorting, this is the basis of the foundation.
import random
import string
class Student:
def __init__(self,name,gender,age):
self._name = name
self._gender = gender
self._age = age
def get_age(self):
return self._age
def print_student(self):
return self._name,self._gender,self._age
# def __str__(self):
# return '%s%s%s'%(self._name,self._gender,self._age)
# __repr__ = __str__##联合上面两个式子可以显示出具体值而不是对象的地址!!!!!!!!
def generate_student_name(num):
list = []
for i in range(num):
randname = ''.join(random.sample(string.ascii_letters,4))
randgender = random.choice(['male','female'])
randage = random.randint(10,40)
s = Student(randname,randgender,randage)
list.append(s)
return list
def sort_student(list):
for i in range(len(list)):
for j in range(1,len(list)-1):
if list[j].get_age()<list[j-1].get_age():
list[j],list[j-1] = list[j-1],list[j]
return list
if __name__ == '__main__':
name = generate_student_name(3)
sort = sort_student(name)
for x in sort:
print(x.print_student())
#如果不用上面两行,也可以用上面对类内置方法进行定义也可以直接显示出要求显示的名字属性,
#不过由于返回的是一个类(注意是类)但显示的是名字,
#所以要进行比较还是要for x in sort:print(x.print_student())
Method 2:
Sorted also comes with the function that comes with Python:
sort = sorted (name, key = lambda Student: Student.get_age ())
uses an anonymous function to specify attribute sorting.
It can be understood here that an anonymous function returns [student object 1, student object 2, student object 3 ...] to its age attribute, so it becomes [student object 1 age, student object 2 age, student object 3 Age ...], and then sort. So sort can also be changed to ** sort = sorted (name, key = lambda x: x.get_age ()) ** because x is just an input variable, which is a representative of an element of name, whatever is called, even if it is a class student
Use the dictionary method:
import random
import string
def generate_student_name(num):
list = []
for i in range(num):
randname = ''.join(random.sample(string.ascii_letters,4))
randgender = random.choice(['male','female'])
randage = random.randint(10,40)
s = {'randname':randname,'randgender':randgender,'randage':randage}
list.append(s)
return list
if __name__ == '__main__':
name = generate_student_name(3)
# sort = sorted(name,key=lambda s:s['randage'])结果是一样的
sort = sorted(name,key=lambda x:x['randage'])
for x in sort:
print(x)