Here's another program form DSF .We are continuing the sorting
techniques.Now lets check out Bubble Sort.Bet you won't find an easier
program than the one's here on Tech Junkieee...If you have then please post it in the comments section so that the readers of TJ would benefit from it .
Lets take a look at the example followed by the program
Program For Bubble Sort Using Java
/**
*
* @author The Cyber Soul
*/import java.io.*;
public class BubbleSort {
public static void main(String a[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("***BUBBLE SORTING***");
int i,n;
System.out.println("Enter the length of Array");
n=Integer.parseInt(br.readLine());
int array[] = new int[n];
System.out.println("Enter the values");
for(i=0;i<n;i++)
{
array[i]=Integer.parseInt(br.readLine());
}
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("***END OF BUBBLE SORT***");
}
public static void bubble_srt( int a[], int n ){
int i, j,t=0;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
}
Program For Bubble Sort Using Java
/**
*
* @author The Cyber Soul
*/import java.io.*;
public class BubbleSort {
public static void main(String a[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("***BUBBLE SORTING***");
int i,n;
System.out.println("Enter the length of Array");
n=Integer.parseInt(br.readLine());
int array[] = new int[n];
System.out.println("Enter the values");
for(i=0;i<n;i++)
{
array[i]=Integer.parseInt(br.readLine());
}
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("***END OF BUBBLE SORT***");
}
public static void bubble_srt( int a[], int n ){
int i, j,t=0;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
}
0 comments:
Post a Comment
Please Feel free to Share your view with us ....