JAVA Program for sorting first half in ascending order and second half in descending

Java program for Sorting first half in ascending order and second half in descending order

Sorting first half in ascending order and second half in descending order

In this article we will learn how to write a java program for sorting first half in ascending order and second half in descending order. Although it sounds a bit difficult but we’ll try to make it as easy as possible. Let’s take an example for understanding what we have to perform

Input array : [3, 5, 2, 7, 9, 1]

Output array : [1, 2, 3, 9, 7, 5]

Algorithm for Sorting first half in ascending order and second half in descending order

  • Step 1 – Initialize a variable len, for accepting the length of the array.
  • Step 2 – Take the input from the user using a for loop.
  • Step 3 – Sort the inputted array in the ascending order.
  • Step 4 – Use two for loops for printing the array
    • Use the first loop from 0 to len/2 for printing the first ascending part of the array.
    • Use the second for loop from len-1 to len/2 for printing the second descending part of the array.

 

Java Code for Sorting first half in ascending order and second half in descending order

import java.util.*;
public class Sort {
    public static void main(String args[])
    {
        int i=0, temp;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the length of the array : ");
        int len = sc.nextInt();
        int arr[]=new int[50];
        System.out.println("Enter the element of the array : ");
        for( i=0;i < len;i++)
        {
            arr[i]=sc.nextInt();
        }
        for( i=0;i < len;i++)
        {
            for(int j=i+1;jarr[j])
                {
                    temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
        }
 //printing first half of the array
       System.out.println("Sorted array ");
        for( i=0;i < len/2;i++)
        {
            System.out.println(arr[i]);
        }
//printing second half of the array
       
        for( i=len-1;i >= len/2;i--)
        {
            System.out.println(arr[i]);
        }

    }
    
}

Output
Enter the length of the array : 
6
Enter the element of the array : 
4
5
2
3
1
6
Sorted array
1
2
3
6
5
4