June 09, 2012

DS: Bubble Sort Program


import java.util.Scanner;

public class Bubblesort {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of the array");
int size = sc.nextInt();
bsort s = new bsort(size);
System.out.println("Elements before sorting");
s.display();
s.bubble();
System.out.println("Elements after sorting");
s.display();
}
}

class bsort {
int a[], N;
Scanner sc = new Scanner(System.in);

public bsort(int size) {
a = new int[size];
N = size;
System.out.println("Enter elements into the array");
for (int i = 0; i < N; i++) {
a[i] = sc.nextInt();
}
}

public void bubble() {
int last = N;
for (int pass = 0; pass < N - 1; pass++) {
int ex = 0;
for (int j = 0; j < last - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
ex = ex + 1;
}
}
if (ex != 0)
last = last - 1;
else
return;
}
}

public void display() {
for (int i = 0; i < N; i++) {
System.out.print(" " + a[i]);
}
System.out.println();
}
}

Output:

Enter size of the array
5
Enter5  elements into the array
96
73
68
63
60
Elements before sorting  
96 73 68 63 60 
Elements after sorting 
60 63 68 73 96                                                                                                                                                                                                   

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts