python中选择排序_使用选择排序对python中的数组进行排序。我该如何优化?

Working on this challenge on HackerRank and got this code to pass 10 out of 15 test cases. It is failing due to timeout error which is HackerRank's way of telling you that the algorithm is not optimized. How can I optimize this code to run on larger input data?

The goal is to figure out the minimum number of swaps necessary to sort an unsorted array.

Update: Each element in the array is distinct.

def minimum_swaps(arr):

"""Returns the minimum number of swaps to re-oder array in ascending order."""

swaps = 0

for val in range(len(arr) - 1, 0, -1):

# Index of max value

max_pos = 0

for index in range(1, val + 1):

if arr[index] > arr[max_pos]:

max_pos = index

# Skip if value is already in sorted position

if max_pos == val:

continue

arr[val], arr[max_pos] = arr[max_pos], arr[val]

swaps += 1

return swaps

解决方案

Look at the code. It has 2 nested loops:

The outer loop iterates over the positions val.

The inner loop finds the index of the value that should be at the index val, i.e., max_pos.

It takes a lot of time just to find the index. Instead, I will compute the index of each value and store it in a dict.

index_of = {value: index for index, value in enumerate(arr)}

(note that because all values in arr are distinct, there should be no duplicated keys)

And also prepare a sorted version of the array: that way it's easier to find the maximum value instead of having to loop over the array.

sorted_arr = sorted(arr)

Then do the rest similar to the original code: for each index visited, use sorted_arr to get the max, use index_of to get its current index, if it's out-of-place then swap. Remember to update the index_of dict while swapping too.

The algorithm takes O(n) operations (including dict indexing/modifying), plus sorting cost of n elements (which is about O(n log n)).

Note: If the array arr only contains integers in a small range, it may be faster to make index_of an array instead of a dict.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值