import json import sys from typing importList defbubble_sort(l: List[int]) -> None: """ In-Place Selection Sort :param l: The unsorted input array. IT WILL BE MUTATED INSIDE THE FUNCTION. """ ... # Your code here. if __name__ == "__main__": l = list(json.load(sys.stdin)) bubble_sort(l) json.dump(l, sys.stdout)
Implementation Limitations
The bubble sort algorithm should be IN PLACE without requesting for more memories.
My answer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import json import sys from typing importList
defbubble_sort(l: List[int]) -> None: n = len(l) for i inrange(n): for j inrange(0, n - i - 1): if l[j] > l[j + 1]: l[j], l[j + 1] = l[j + 1], l[j]
if __name__ == "__main__": l = list(json.load(sys.stdin)) bubble_sort(l) json.dump(l, sys.stdout)
算法解释
冒泡排序
对相邻两个对象进行比较,如果前面的比后面的大,则进行换位
当遍历换位完整个列表时,再遍历一次判断是否存在前者大于后者的元素,如果没有,则返回列表
Selection Sort
Selection sort is one of the most basic sorting algorithms in computer science. It has an O(n2) complexity so is not commonly used to sort large arrays. The algorithm of selection sort is simple: It iterates the array and finds the smallest (or largest, depending on the sorting order) value, and pushes the value to a sorted sublist of items which is built up from left to right at the front. It repeatedly iterates the array unless there is no element left.
Specifications
INPUT A JSON-encoded list (length ranged [0,10000]) of integers ranged [−214,214].
defselection_sort(l: List[int]) -> None: """ In-Place Selection Sort :param l: The unsorted input array. IT WILL BE MUTATED INSIDE THE FUNCTION. """ ... # Your code here.
if __name__ == "__main__": l = list(json.load(sys.stdin)) selection_sort(l) json.dump(l, sys.stdout)
Implementation Limitations
The selection sort algorithm should be IN PLACE without requesting for more memories. For example, the following selection-sort-like algorithm can also sort arrays but is NOT considered correct:
defselection_sort(l: List[int]) -> None: n = len(l) for i inrange(n): min_idx = i for j inrange(i+1, n): if l[j] < l[min_idx]: min_idx = j l[i], l[min_idx] = l[min_idx], l[i] if __name__ == "__main__": l = list(json.load(sys.stdin)) selection_sort(l) json.dump(l, sys.stdout)