Algorithm - Bubble sort

Now we are going to look up some algorithms.

Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order

Example in Java:

public class BubbleSort {

    public static void bubble_sort(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap temp and arr[i]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    private static void swapNumbers(int i, int j, int[] array) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

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

    public static void main(String[] args) {
        int[] input = {5, 3, 9, 6, 17, 12, 16, 0, 1};
        bubble_sort(input);
        System.out.println("Sorted Array");
        printNumbers(input);
    }
}

Output:
Sorted Array

0 1 3 5 6 9 12 16 17 

Comments

Popular posts from this blog

Clear the app data programmatically in android

convert an integer to a string in java

Print the large string values in android log cat.