Algorithm - Insertion Sort

Insertion Sort
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It's not much efficient in large sets of data.

Solution

public class InsertionSort {

    public static void main(String arg[]) {
        int[] arr1 = {84, 43, 17, 65, 6, 19, 83, 4};
        int[] arr2 = doSort(arr1);
        for (int i = 0; i < arr2.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(arr2[i]);
        }
    }

    public static int[] doSort(int[] array) {

        int temp;
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j > 0; j--) {
                if (array[j] < array[j - 1]) {
                    temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
                }
            }
        }
        return array;
    }
}

Result:
4, 6, 17, 19, 43, 65, 83, 84

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

Dependencies vs Dev Dependencies in Flutter

What's new in android 14?