Java program to sort elements of an array in ascending and descending order

Sorting an Array in Ascending and Descending order

sorted array is an array data structure in which each element is sorted in numerical, alphabetical, or some other order, and placed at equally spaced addresses in computer memory. Here we will be using an simple sorting algorithm to sort the array in ascending and then descending order.

Sorting_in_Java

Algorithm

  • Input size of array n with n space separated integer.
  • Run outer for loop from 0 to n-1.
  • Run another inner loop from 0 to n-1-i to place newly selected element at it’s correct position.
  • Inside inner loop compare the adjacent elements if the the elements are not in correct order swap them.
  • Repeat the step 2 to 4 until we get an sorted array in ascending order .
  • Now , for sorting an array in descending array we just need to take two variable i and j.
  • Assign i with zero and j with n-1 and loop until i is less than to j.
  • Inside loop swap the elements of array which are at position i and j .
  • At , the end we will get an sorted array in descending order.

CODE IN JAVA

import java.util.*;

class Solution
{
public static void main (String[]args)
{

Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int arr[] = new int[n];

for (int i = 0; i < n; i++)
arr[i] = sc.nextInt ();
int countOfSwap = 0;

for (int i = 0; i < n - 1; i++)
{
countOfSwap = 0;
for (int j = 0; j < n - 1 - i; j++)
{

if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
countOfSwap++;
}
}
if (countOfSwap == 0)
break;
}

System.out.print ("Ascending order = ");

for (int i = 0; i < n; i++)
System.out.print (arr[i] + " ");

for (int i = 0, j = n - 1; i < j; i++, j--)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println ();
System.out.print ("Desccending order = ");

for (int i = 0; i < n; i++)
System.out.print (arr[i] + " ");
}
}

Output :-

Ascending order = 2 4 6 8 9
Desccending order = 9 8 6 4 2

TIME AND SPACE COMPLEXITY

Time Complexity 

O(n^2)

Space Complexity

O(1)