Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
Sign in with GoogleSign in with Google
Python Code to sort first half in ascending order and second half in descending order
October 22, 2020
Sort first half in ascending and second half in descending order
In this paragraph given an array of integers we have to sort the first half of the array in ascending order and second half in descending order using Python library function.In Ascending order means elements are sorted in smaller to larger element and In descending order means the element are sorted in larger to smaller element. For Example Enter the array size 6 Enter array elements 5 44 11 9 99 34 First sort the elements 5 9 11 34 44 99 Sorted first half in ascending order and second half in descending 5 9 11 99 44 34
Working needed for sorting first half in ascending and second half in descending order
Step 1: Initialize and declare array. Step 2: Take the input in the array Step 3: First sort the elements of the array Step 4: Then print the first half in ascending order. Step 5: After that print second half in descending order.
Sort first half in ascending order and second half in descending using Python Code
size=int(input("ENTER ARRAY SIZE "))
arr=[]
print("Enter the array elements")
for i inrange(size):
element=int(input())
arr.append(element)
arr.sort()
half=arr[size//2:]
half.sort(reverse=True)
out=arr[:size//2]+half
print("Sorted first half in ascending order and second half in descending",*out,sep="\n")
Output
ENTER ARRAY SIZE 7
Enter the array elements
4
3
6
8
2
1
99
Sorted first half in ascending order and second half in descending
1
2
3
99
8
6
4
Login/Signup to comment