I have given the sample input and sample output.
The EVEN index is only sorted and the ODD index are left as it is.
Sample Input :
5
3 9 1 44 6
Sample Output :
1 9 3 44 6
CodePudding user response:
Here's what you can do using modified bubble sort technique:
def sortEvens(arr):
arrLen = len(arr)
for i in range(0, arrLen, 2): # Jump by 2 units
for j in range(0, arrLen-i-2, 2): # Jump by 2 units
if arr[j] > arr[j 2]: # Comparing alternative elements
temp = arr[j]
arr[j] = arr[j 2]
arr[j 2] = temp
return arr
arr = [10, 45, 0, -34, 5, -899, 4]
print(sortEvens(arr))
# OUTPUT : [0, 45, 4, -34, 5, -899, 10]
positions-> 0 1 2 3 4 5 6
CodePudding user response:
You can assign a striding subscript with the sorted values of that same subscript:
arr = [3, 9, 1, 44, 6]
arr[::2] = sorted(arr[::2]) # assign even items with their sorted values
print(arr) # [1, 9, 3, 44, 6]