Skip to content

Instantly share code, notes, and snippets.

@AnimeshShaw
Created September 12, 2013 18:19
Show Gist options
  • Save AnimeshShaw/6541728 to your computer and use it in GitHub Desktop.
Save AnimeshShaw/6541728 to your computer and use it in GitHub Desktop.
BubbleSort implemented in Java
import java.util.Scanner;
public class BubbleSort {
private static void swap(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
private static boolean checkMin(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
private static void display(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
}
private static void BubbleSort(Comparable[] a) {
int n = a.length;
boolean sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0; i < n - 1; i++) {
if (checkMin(i, i+1)) {
swap(a,i+1,i);
sorted = false;
}
}
n--;
}
}
public static void main(String[] args) {
String a;String[] b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the data to be sorted seperated by space :-");
a = sc.nextLine();
System.out.println("\nSort using Bubble Sort");
b = a.trim().split(" ");
BubbleSort(b);
display(b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment