I am working on an assignment and I am really struggling to figure out what I am doing wrong. I am new to Python, and honestly, I barely understand the code I have cobbled together so far.
What I have currently is:
array=[int(n) for n in input().split()]
for i in range(len(array)):
max_index = i
for j in range(i+1, len(array)):
if int(array[j]) > int(array[max_index]):
max_index = j
array[i],array[max_index] = array[max_index],array[i]
print(array)
With the input of
50 40 20 10 30
I get:
[50, 40, 20, 10, 30]
[50, 40, 20, 10, 30]
[50, 40, 30, 10, 20]
[50, 40, 30, 20, 10]
[50, 40, 30, 20, 10]
What I need is:
[50, 40, 20, 10, 30]
[50, 40, 20, 10, 30]
[50, 40, 30, 10, 20]
[50, 40, 30, 20, 10]
The only difference between the actual and expected output is that it outputs the sorted array an additional time. If you're looking to stop sorting whenever the array is sorted, you can add a break
statement to terminate the loop early:
def is_sorted_descending(array):
for i in range(len(array) - 1):
if array[i] < array[i + 1]:
return False
return True
for i in range(len(array)):
max_index = i
for j in range(i+1, len(array)):
if int(array[j]) > int(array[max_index]):
max_index = j
array[i],array[max_index] = array[max_index],array[i]
print(array)
if is_sorted_descending(array):
break
See the below code, here checking that array is sorted using a flag and stop processing for loop after sorted, it will improve time complexity of algorithm.
array=[int(n) for n in input().split()]
for i in range(len(array)):
max_index = i
is_sorted = True
for j in range(i + 1, len(array)):
if int(array[j]) > int(array[max_index]):
max_index = j
is_sorted = False
if (is_sorted == True):
break
array[i],array[max_index] = array[max_index],array[i]
print(array)
Input: 50 40 30 20 10 (ie sorted array and it prints None as its sorted)
Output:
Input: 10 20 30 40 50 (ie unsorted array and it prints till it sorted & break)
Output:
[50, 20, 30, 40, 10]
[50, 40, 30, 20, 10]
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.