How to Create a Program to Perform Sorting of Array in Core Java

In this tutorial how to Perform Sorting of Array in Core Java  is shown.

Code:

Sort.java

class SortArray
{
public static void main(String args[])
{
if(args.length<1)
{
System.out.println(“No data passed”);
}
else
{
int n=Integer.parseInt(args[0]);
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(args[i+1]);
}

System.out.println(“Original Array:”);
for(int i=0;i<n;i++)
{
System.out.println(“a[“+i+”]=”+a[i]);
}

for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(a[i]>a[j])
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}

System.out.println(“Sorted Array in Ascending Order:”);

for(int i=0;i<n;i++)
{
System.out.println(“a[“+i+”]=”+a[i]);
}

for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(a[i]<a[j])
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}

System.out.println(“Sorted Array in Descending Order:”);

for(int i=0;i<n;i++)
{
System.out.println(“a[“+i+”]=”+a[i]);
}
}
}
}

Add a Comment

Your email address will not be published.