Monday, December 4, 2017

BubbleSort Java Program

import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {
 int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
 Bsort(input);
 Arrays.sort(input);
 for (int i = 0; i < input.length; i++) {
     System.out.print(input[i] + " ");
 }
    }

    private static void Bsort(int[] input) {
 int n = input.length;
 int k;

 for (int m = n; m >= 0; m--) {
     for (int i = 0; i < n - 1; i++) {
  k = i + 1;
  if (input[i] > input[k])
      swap(i, k, input);
     }
     printArray(input);
 }
    }

    private static void printArray(int[] input) {
 for (int i = 0; i < input.length; i++) {
     System.out.print(input[i] + " ");
 }
 System.out.println("\n");
    }

    private static void swap(int i, int k, int[] input) {
 int temp;
 temp = input[i];
 input[i] = input[k];
 input[k] = temp;
    }

}

No comments: