Write a Program which sorts an array of type integer.

Code:

import java.util.Scanner;
class P3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,n,j;
int loc,small,temp,k;
System.out.println("ENTER TOTAL NUMBER OF ELEMENTS OF ARRAY:=");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("ENTER ELEMENTS:=");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("UNSORTED ELEMENTS ARE:=");
for(i=0;i<n;i++)
{
System.out.print("|&nbsp;&nbsp; "+a[i]+"&nbsp;&nbsp; |");
}
for(i=1;i<n;i++)
{
small=a[i-1];
loc=i-1;
for(j=i;j<n;j++)
{
if(a[j]<small)
{
small=a[j];
loc=j;
}
}
if(loc!=(i-1))
{
temp=a[i-1];
a[i-1]=a[loc];
a[loc]=temp;
}
}
System.out.println();
System.out.println("SORTED ELEMENTS ARE:=");
for(i=0;i<n;i++)
{
System.out.print("|&nbsp;&nbsp; "+a[i]+"&nbsp;&nbsp; |");
}
}
}

OUTPUT:

(Visited 119 times, 1 visits today)
Share with Friends :
Written by: