Tuesday, December 13, 2011

Bubble Sort program in JAVA(Ascending order)

import java.util.*;
import java.io.*;
class sort
{
public static void main(String args[])throws Exception
{
 int arr[]=new int[100];
 int i,j,temp;
 System.out.println("How many numbers you want to sort:");
 BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
 int n= Integer.parseInt(k.readLine());
 System.out.println("Enter the values one by one");
 for(i=0;i<n;i++)
 {
 arr[i]=Integer.parseInt(k.readLine());
 }
 for(i=0;i<n-1;i++)
 {
 for(j=i;j<n;j++)
 {
 if(arr[i]>arr[j])
 {
 temp=arr[i];
 arr[i]=arr[j];
 arr[j]=temp;
 }
 }
 }
 System.out.println("Numbers after sorting:");
 for(i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}

}

output:
How many numbers you want to sort:
5
Enter the values one by one
4
3
7
6
1
Numbers after sorting:
1
3
4
6
7