insertion sort
insertion sort Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Time Complexity: O(n*2) Auxiliary Space: O(1) Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. Algorithmic Paradigm: Incremental Approach Sorting In Place: Yes Stable: Yes Online: Yes Uses: Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array. https://www.geeksforgeeks.org/insertion-sort/ Notes: this code corresponds to the the picture example public void insertionSort(int[] array){ int n = array.length; for(int i = 1; i < n; i++){ int key = array[i]; int j = i - 1; while(j >= 0 && array[j] > key){ array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } } // why use only static , instead of also having public, private class InsertionSort{ void insertionSort(int[] array){ int n = array.length; for(int i = 1; i < n; i++){ int key = array[i]; int j = i - 1; while(j >= 0 && array[j] > key){ array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } } // a utility function to print array of size n static void printArray(int[] array){ int n = array.length; for(int i = 0; i < n; i++){ System.put.println(); } } public static void main(String[] args){ int[] array = {12, 11, 13, 5, 6}; InsertionSort ob = new InsertionSort(); ob.sort(array); printArray(array); } }
posted on 2018-09-20 18:01 猪猪🐷 阅读(113) 评论(0) 收藏 举报
浙公网安备 33010602011771号