In this article we will learn to implement sorting an array in Java. A Java program is provided below to read a list of numbers and sort them.
I have used exchange sort to sort the array in ascending order.
The program is as follows:
import java.util.*;
class Driver
{
static void printArray(int arr[], int n)
{
System.out.println("Array elements are: ");
for(int i : arr)
System.out.print(i + " ");
System.out.print("\n");
}
static int[] sort(int arr[], int n)
{
//Exchange sort to sort in ascending order
for(int i = 0; i < n - 1; i++)
{
for(int j = i + 1; j < n; j++)
{
if(arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of elements: ");
int n = input.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++)
{
a[i] = input.nextInt();
}
System.out.println("After sorting: ");
printArray(sort(a, n), n);
}
}
Input and Output of the above program is given below:
Enter no. of elements:
6
5 3 -1 0 7 2
After sorting:
Array elements are:
-1 0 2 3 5 7
If you need further explanation for this program, please comment below.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply