Saturday, July 19, 2014

Bubble Sort Algorithm using Java

In Bubble Sort, smaller elements bubbles to top of list in ascending sorting hence it's called Bubble Sort.

How it works :
  1. In Bubble Sort, You take first element and second element initially and compare both elements.
  2. If second element is smaller than first element then you swipe places. how? using temp :) as below
  3. You keep doing same meaning stepping through array and comparing element with pair of adjacent elements until no swapping required and you have sorted array
Java Program using Bubble Sort Algorithm :


package com.anuj.algorithms;

import java.util.Arrays;

/**
 *
 * @author Anuj Patel
 * @source goldenpackagebyanuj.blogspot.com
 */
public class BubbleSort {

    protected void doBubbleSort(int data[], String sortingType) {
        int temp;
        for (int i = 0; i < data.length; i++) {
            //data[i] - individual array values
            for (int j = 0; j < data.length - 1; j++) {
                if (sortingType.equalsIgnoreCase("Ascending")) {
                    if (data[j] > data[j + 1]) {
                        temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;                        
                    }                    
                } else if (sortingType.equalsIgnoreCase("Descending")) {
                    if (data[j] < data[j + 1]) {
                        temp = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = temp;
                    }
                }
            }
        }
        System.out.println("After " + sortingType + " Sorting : " + Arrays.toString(data));
   }

    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();

        int data[] = {1, 2, 33, 56, 8, 31};
        System.out.println("Before Sorting : " + Arrays.toString(data));
        bubbleSort.doBubbleSort(data, "Ascending");
        bubbleSort.doBubbleSort(data, "Descending");
    }
}
Output :
run:
Before Sorting : [1, 2, 33, 56, 8, 31]
After Ascending Sorting : [1, 2, 8, 31, 33, 56]
After Descending Sorting : [56, 33, 31, 8, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)
Author : Anuj Patel Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment