Sunday, August 26, 2018

Sorting: Bubble Sort


https://www.hackerrank.com/challenges/ctci-bubble-sort/problem

static void countSwaps(int[] a) {
        int count = 0;
        boolean isSorted = false;
        int lastUnsorted = a.length - 1;
        // Every time the last element is sorted
        while (!isSorted) {
            isSorted = true;
            for (int i = 0; i < lastUnsorted; i++) {
                if (a[i] > a[i + 1]) {
                    swap(a, i, i + 1);
                    isSorted = false;
                    count++;
                }
            }
            lastUnsorted--;
        }

        System.out.printf("Array is sorted in %d swaps.%n", count);
        System.out.printf("First Element: %d%n", a[0]);
        System.out.printf("Last Element: %d%n", a[a.length - 1]);
    }
    static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

No comments:

Post a Comment