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.

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

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:

#Take input from user separated by space
a=list(map(int,input("Enter array ").split()))
#Create empty list x and y
x=[] y=[]

#n will store length of a n=len(a)

#Run loop from 0 to n//2 for i in range(n//2):    x.append(a[i])

#Run loop from n//2 to n for i in range(n//2,n):    y.append(a[i])
#Sort the array is ascending order
x.sort()

#Sort the array y in descending order y.sort(reverse=True)

#Print the result print("Resultant array",*(x+y))
#test case 1
Enter array  87 56 23 45 9 67 55 89
Resultant array  23 45 56 87 89 67 55 9

#test case 2
Enter array 8 5 2 4
Resultant array 5 8 4 2

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:

#Input elemenets of list separated by space

a=list(map(int,input("Enter array ").split()))

#Create array x and y using slicing

#x will have all the elements from 0 index till (len(a)//2) (excluded)

#y will have all the elements from index: (len(a)//2) till end of array x=a[:len(a)//2] y=a[len(a)//2:]

#Sort the array x in ascending order x.sort()   

#Sort the array y in reverse order     y.sort(reverse=True)
#Now print the array x and y 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