Advertisement
Psycho_Coder

Bubble Sort in Java

Oct 10th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class BubbleSort {
  4.  
  5.     private static void swap(Comparable[] a, int i, int j) {
  6.         Comparable t = a[i];
  7.         a[i] = a[j];
  8.         a[j] = t;
  9.     }
  10.  
  11.     private static boolean checkMin(Comparable v, Comparable w) {
  12.         return v.compareTo(w) < 0;
  13.     }
  14.  
  15.     private static void display(Comparable[] a) {
  16.         for (int i = 0; i < a.length; i++) {
  17.             System.out.print(a[i] + "\t");
  18.         }
  19.     }
  20.  
  21.     private static void BubbleSort(Comparable[] a) {
  22.         int n = a.length;
  23.         boolean sorted = false;
  24.         while (!sorted) {
  25.             sorted = true;
  26.             for (int i = 0; i < n - 1; i++) {
  27.                 if (checkMin(i, i+1)) {
  28.                     swap(a,i+1,i);
  29.                     sorted = false;
  30.                 }
  31.             }
  32.             n--;
  33.         }
  34.     }
  35.  
  36.     public static void main(String[] args) {
  37.         String a;String[] b;
  38.         Scanner sc = new Scanner(System.in);
  39.         System.out.println("Enter the data to be sorted seperated by space :-");
  40.         a = sc.nextLine();
  41.                
  42.         System.out.println("\nSort using Bubble Sort");        
  43.         b = a.trim().split(" ");
  44.         BubbleSort(b);
  45.         display(b);        
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement