2. Basic data structure and algorithms in java - Bubble sort

Bubble sort

Bubble sort is very easy to understand, use two for loop to sort the array, and the time complexity is O(n2).
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

public class Study {
    /**
     * main function to sort array using bubble sort
     *
     * @param args
     */
    public static void main(String[] args) {
        int[] arr = {1, -10, -2, 3, 8, 100, -100, 2, 6, 25};
        print(arr);
        System.out.println();
        bubbleAsc(arr);
        // bubbleDes(arr);
        print(arr);
    }

    /**
     * ascending order
     *
     * @param arr
     */
    private static void bubbleAsc(int[] arr) {
        // flag is used to mark whether swap happens in one single bubble i from 0 to lastUnsortedIndex
        boolean flag = false;
        // lastUnsortedIndex means the last index of the unsorted array, the original value is arr.length-1
        // since the input array is unsorted at beginning
        for (int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
            // each bubble loop we sort i from 0 to lastUnsortedIndex
            for (int i = 0; i < lastUnsortedIndex; i++) {
                if (arr[i] > arr[i + 1]) {
                    swap(arr, i, i + 1);
                    flag = true;
                }
            }
            if(!flag) break;
        }
    }

    /**
     * descending order
     *
     * @param arr
     */
    private static void bubbleDes(int[] arr) {
        // flag is used to mark whether swap happens in one single bubble i from 0 to lastUnsortedIndex
        boolean flag = false;
        for (int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
            for (int i = 0; i < lastUnsortedIndex; i++) {
                if (arr[i] < arr[i + 1]) {
                    swap(arr, i, i + 1);
                }
            }
        }
    }

    /**
     * swap values
     *
     * @param arr
     * @param i
     * @param j
     */
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /**
     * print the array
     *
     * @param arr
     */
    private static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print("arr[" + i + "] = " + arr[i] + " ");
        }
    }
}

Result
arr[0] = 1 arr[1] = -10 arr[2] = -2 arr[3] = 3 arr[4] = 8 arr[5] = 100 arr[6] = -100 arr[7] = 2 arr[8] = 6 arr[9] = 25
arr[0] = 100 arr[1] = 25 arr[2] = 8 arr[3] = 6 arr[4] = 3 arr[5] = 2 arr[6] = 1 arr[7] = -2 arr[8] = -10 arr[9] = -100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值