This article example describes the Python implementation of the algorithm to find any kth largest number in the array. Shared for your reference, as follows:
Mimics the partion method, searching in the second half when high=low is less than k, and in the first half when high=low is greater than k. Unlike fast sort, the ordering is reduced by half each time.
def partitionOfK(numbers, start, end, k): if k < 0 or numbers == [] or start < 0 or end >= len(numbers) or k > end: return None low = start high = end key = numbers[start] while low < high: while low < high and numbers[high] >= key: high -= 1 numbers[low] = numbers[high] while low < high and numbers[low] <= key: low += 1 numbers[high] = numbers[low] numbers[low] = key if low < k: return partitionOfK(numbers, start + 1, end, k) elif low > k: return partitionOfK(numbers, start, end - 1, k) else: return numbers[low] numbers = [3,5,6,7,2,-1,9,3] print(sorted(numbers)) print(partitionOfK(numbers, 0, len(numbers) - 1, 5))
Output: the fifth most sorted number is returned
[-1, 2, 3, 3, 5, 6, 7, 9]
6
PS: Here is another demo tool on sorting for your reference:
Online animated demonstration of insertion/selection/bubbling/merging/hill/fast sort algorithm process tool:
http://tools./aideddesign/paixu_ys
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.