เมื่อจำเป็นต้องเลือกองค์ประกอบที่เล็กที่สุดลำดับที่ n จากรายการในความซับซ้อนของเวลาเชิงเส้น ต้องใช้สองวิธี วิธีหนึ่งในการหาองค์ประกอบที่เล็กที่สุด และอีกวิธีหนึ่งที่แบ่งรายการออกเป็นสองส่วน ส่วนนี้ขึ้นอยู่กับค่า 'i' ที่ผู้ใช้กำหนด ตามค่านี้ รายการจะถูกแยกออกและกำหนดองค์ประกอบที่เล็กที่สุด
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
def select_smallest(my_list, beg, end, i):
if end - beg <= 1:
return my_list[beg]
pivot_val = start_partition(my_list, beg, end)
k = pivot_val - beg + 1
if i < k:
return select_smallest(my_list, beg, pivot_val, i)
elif i > k:
return select_smallest(my_list, pivot_val + 1, end, i - k)
return my_list[pivot_val]
def start_partition(my_list, beg, end):
pivot_val = my_list[beg]
i = beg + 1
j = end - 1
while True:
while (i <= j and my_list[i] <= pivot_val):
i = i + 1
while (i <= j and my_list[j] >= pivot_val):
j = j - 1
if i <= j:
my_list[i], my_list[j] = my_list[j], my_list[i]
else:
my_list[beg], my_list[j] = my_list[j], my_list[beg]
return j
my_list = input('Enter the list of numbers.. ')
my_list = my_list.split()
my_list = [int(x) for x in my_list]
i = int(input('Enter the value for i.. '))
ith_smallest = select_smallest(my_list, 0, len(my_list), i)
print('The result is {}.'.format(ith_smallest)) ผลลัพธ์
Enter the list of numbers.. 43 12 67 89 99 0 Enter the value for i.. 3 The result is 43.
คำอธิบาย
-
มีการกำหนดเมธอดชื่อ 'select_smallest' ซึ่งรับรายการ จุดเริ่มต้น จุดสิ้นสุด และค่า 'i' เป็นพารามิเตอร์
-
มีการกำหนดวิธีการอื่นที่ชื่อว่า 'start_partition' ซึ่งแบ่งรายการออกเป็นสองส่วนขึ้นอยู่กับค่าของ 'i'
-
วิธีนี้เรียกว่าวิธี 'select_smallest'
-
'select_smallest' จะถูกเรียกอีกครั้งภายในฟังก์ชันเดียวกัน นี่คือวิธีการทำงานของการเรียกซ้ำ
-
ตัวเลขจะถูกนำมาเป็นอินพุตจากผู้ใช้
-
โดยจะแบ่งตามค่าเริ่มต้น
-
ซ้ำแล้วซ้ำเล่า
-
ค่าสำหรับ 'i' ถูกนำมาจากผู้ใช้
-
ตามค่า 'i' นี้ รายการจะถูกแบ่งออกเป็นสองส่วน
-
วิธี 'select_smallest' ถูกเรียกในรายการใดรายการหนึ่ง
-
เอาต์พุตจะแสดงบนคอนโซล