Tuesday, November 9, 2010

Bubble sort using Java

Working :

In this sorting technique we compare the first value with the next and swap the elements if the first is higher than second. Suppose there are 'n' numbers then we making n-1 comparisions in for sorting every number.

Code :

Bubble.java


//program for bubble sort

import java.util.*;

public class Bubble
{
static void bubblesort(int a[])
{
int t;
for(int i=a.length-2;i >= 0;i--)
for(int j = 0;j <= i; j++) if(a[j]>a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}

public static void main(String args[])
{
System.out.println("Enter number of elements you wish to sort : ");
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

//declare array of n elements

int a[] = new int[n];

//scan array from 0 to n-1 locations

for(int i = 0; i <= n-1;i++)
{
System.out.print("\nEnter element " + (i+1) + " : ");
a[i] = sc.nextInt();
}
System.out.println("\nOriginal array : ");
for(int i=0;i<=n-1;i++)
System.out.print(a[i] + " ");

//sort the array

bubblesort(a);

//print sorted array

System.out.println("\nSorted array : ");
for(int i=0;i<=n-1;i++)
System.out.print(a[i] + " ");

}//end of main
}//end of class Bubble


Output :


Enter number of elements you wish to sort :
5

Enter element 1 : 5

Enter element 2 : 4

Enter element 3 : 1

Enter element 4 : 2

Enter element 5 : 6

Original array :
5 4 1 2 6
Sorted array :
1 2 4 5 6

0 comments:

Post a Comment