bubble sort int array - Java java.lang

Java examples for java.lang:int Array

Description

bubble sort int array

Demo Code



public class Main{
    public static void main(String[] argv) throws Exception{
        int[] arr = new int[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(bubbleSort(arr)));
    }/*w  ww  .j  a  va 2s  . c  om*/
    /**
     * bubble sort
     */
    public static int[] bubbleSort(int[] arr) {
        int swapCount = 0;
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[i] < arr[j]) {
                    ArrayUtil.swap(arr, i, j);
                    swapCount++;
                }
            }
        }
        System.out.println("swap count(bubble sort): " + swapCount);
        return arr;
    }
    /**
     * swap two element in array
     */
    private static int[] swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return arr;
    }
}

Related Tutorials