简体   繁体   中英

How do I swap numbers in an array?

I was curious as how to write a code in order to swap the first element in my array with the smallest number and do the same with the largest with the last element without sorting the whole array and just swapping those 4 numbers.

You'll have to iterate the whole array to find the index of either minimum or maximum element. After you searched through, the swapping is really easy. For example:

numbers = [3,6,2,7,1,10,2]
current_min = current_max = numbers[0]
min_idx = max_idx = 0 
for idx, num in enumerate(numbers):
    if num < current_min:
        current_min = num
        min_idx = idx
    elif num > current_max:
        current_max = num
        max_idx = idx
# do the swap
numbers[0], numbers[min_idx] = numbers[min_idx], numbers[0]
numbers[-1], numbers[max_idx] = numbers[max_idx], numbers[-1]

In Order to find smallest or largest to swap, you will still need to sort. You may have the smallest at the last index and to find that you will have to compare each of the element once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM