insert sort the most stable sort algorithm times of comparing equals times of swap two times as fast as bubble sort a little faster than select sort - Java Collection Framework

Java examples for Collection Framework:Array Sort

Description

insert sort the most stable sort algorithm times of comparing equals times of swap two times as fast as bubble sort a little faster than select sort

Demo Code


//package com.java2s;

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(insertSort(arr)));
    }/*  ww w .  j  ava  2 s  .com*/

    /**
     * insert sort
     * <p/>
     * the most stable sort algorithm
     * <p/>
     * times of comparing equals times of swap
     * <p/>
     * two times as fast as bubble sort
     * <p/>
     * a little faster than select sort
     */
    public static int[] insertSort(int[] arr) {
        int swapCount = 0;
        for (int i = 1; i < arr.length; i++) {
            int cursor = i;
            while (cursor > 0 && arr[cursor - 1] > arr[cursor]) {
                swap(arr, cursor--, cursor);
                swapCount++;
            }
        }
        System.out.println("swap count(insert 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