# JAVA Program for sorting first half in ascending order and second half in descending ## 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;        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; j < len; j++)	        {	            if (arr[i] > arr[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```

### One comment on “JAVA Program for sorting first half in ascending order and second half in descending”

• Shubham

public class JavaApplication1
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
int n;
n = obj.nextInt();
int a[] = new int[n];
for(int i =0;i<n;i++)
{
a[i]=obj.nextInt();
}
for(int x=0;x<(n+1)/2;x++)
{
for(int y=x+1;y<(n+1)/2;y++)
{
if(a[y]<a[x])
{
int temp;
temp = a[x];
a[x]=a[y];
a[y]=temp;
}
}
}

for(int p=n/2;p<n;p++)
{
for(int q=p+1;q<n;q++)
{
if(a[p]<a[q])
{
int temp;
temp = a[p];
a[p]=a[q];
a[q]=temp;
}
}
}
for(int i =0;i<n;i++)
{
System.out.print(a[i]+" ");
}

}
} 10