Program to Sort first half in ascending order and second half in descending order in an array

python program for sorting the first half of an array in ascending order and the second half in descending order

Sort first half array in ascending and second half in descending order

Here we will use topics like slicing in python and in-built sorting function in python. Slicing will split the array or string by the indices as parameters. ” : ” operator is used for slicing. Sort() function is used to sort the given array (both in ascending order or descending order).
arr.sort() is used to sort array in ascending order.
arr.sort(reverse=True) is used to sort array in descending order.

 

Working:

  • Step 1: Read the array
  • Step 2: intialize two empty arrays (x and y here)
  • Step 3:set n to length of arry
  • Step 4: append elements of  first half of the array to x , and remaining half to y using for loop and append function
  • Step 5: Sort array x in ascending order and sort array y in descending order
  • Step 6: Concatenate both x and y arrays using + operator

Python code:

Solution 1:

a=list(map(int,input(“Enter array “).split()))
x=[]
y=[]
n=len(a)
for i in range(n//2):
    x.append(a[i])
for i in range(n//2,n):
    y.append(a[i])
x.sort()
y.sort(reverse=True)
print(“Resultant array”,*(x+y))
Enter array  87 56 23 45 9 67 55 89 
Resultant array  23 45 56 87 89 67 55 9

Working:

  • Step 1: Read an array
  • Step 2: slice the first part of array and store that in one array
  • Step 3: Slice the second part of array and store that in another array
  • Step 4: sort the first array in ascending order
  • Step 5: Sort the second array in descending order
    Step 6: concatenate the two arrays (using plus operator )and print

Solution 2:

a=list(map(int,input(“Enter array “).split()))
#for slicing array
x=a[:len(a)//2]
y=a[len(a)//2:] 
#for sorting array
x.sort()        
y.sort(reverse=True
#for printing array
print(“Resultant array”,*(x+y)) 
Enter array 87 56 23 45 9 67 55 89
Resultant array 23 45 56 87 89 67 55 9