华为机试HJ101输入整型数组和排序标识,对其元素按照升序或降序进行排序
题目:
输入整型数组和排序标识,对其元素按照升序或降序进行排序
想法:
通过快速排序对序列进行排序,按照指定排序标识的要求输出序列
input_number = input()
input_list = input().split(" ")
input_list = [int(l) for l in input_list]
flag = input()
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
def qucik_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
qucik_sort(arr, low, pi-1)
qucik_sort(arr, pi+1, high)
return arr
result = qucik_sort(input_list, 0, int(input_number)-1)
result = [str(r) for r in result]
if flag == "1":
print(" ".join(result[::-1]))
else:
print(" ".join(result))