Showing posts with label Bubble sort. Show all posts
Showing posts with label Bubble sort. Show all posts

Wednesday, 11 April 2012

Java bubble sort with ArrayList and custom args

Bubble sort: http://en.wikipedia.org/wiki/Bubble_sort

As a bit of fun I wrote my own version of the bubble sort algorithm.

package bubblesort;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Java bubble sort example: This class shows how to sort an array list of
 * Integers using the bubble sort algorithm. Enter numbers as arguments to be
 * sorted.
 *
 * @author rsharp 9/4/12
 */
public class BubbleSort {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        if (args.length > 0) {

            ArrayList<Integer> numbersToSort = new ArrayList<Integer>();

            for (String arg : args) {
                try {
                    numbersToSort.add(Integer.parseInt(arg));
                } catch (NumberFormatException ex) {
                    System.out.println(arg + " is not a number. Please enter only numbers into the bubble sort!");
                }
            }

            //print array before sorting using bubble sort algorithm
            System.out.println("Array before the bubble sort");
            for (int i : numbersToSort) {
                System.out.print(i + " ");
            }

            //sort an array using bubble sort algorithm
            bubbleSort(numbersToSort);

            System.out.println("");

            //print array after sorting using bubble sort algorithm
            System.out.println("Array after bubble sort");
            for (int i : numbersToSort) {
                System.out.print(i + " ");
            }

        } else {
            System.out.println("Please enter a list of numbers to bubble sort!");
        }

    }

    /**
     * This method performs the bubble sort
     * @param numbersToSort
     */
    private static void bubbleSort(ArrayList<Integer> numbersToSort) {

        int temp = 0;
        for (int i = 0; i < numbersToSort.size() - 1; i++) {
            for (int j = 1; j < (numbersToSort.size() - i); j++) {
                if (numbersToSort.get(j - 1) > numbersToSort.get(j)) {
                    //swap the elements!
                    temp = numbersToSort.get(j - 1);
                    numbersToSort.set(j - 1, numbersToSort.get(j));
                    numbersToSort.set(j, temp);
                }

            }
        }
    }
}

You can run this from the command line with arguments. There is error checking for if no or incorrect arguments are sent in:

java bubblesort.BubbleSort 10 2 7 8 3 1 6 9 5 4