Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Arrays » Sorting an array in Java
Suryateja Pericherla Categories: Arrays. No Comments on Sorting an array in Java
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

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.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory