[TOC]
Inserting a Sort program code
Package Com.uplooking.bigdata.datastructure;import Java.util.arrays;public class Insertsort {public static void main (S Tring[] args) {int[] arr = {8,-2, 3, 9, 0, 1, 7, 6}; System.out.println ("Before sorting:" + arrays.tostring (arr)); Insertsort (arr); System.out.println ("After sorting:" + arrays.tostring (arr)); }/** * Insert sort: * View inserts an element into the proper position of an ordered set * src: {8,-2, 3, 9, 0, 1, 7, 6} * Assuming the array length is n * First Tour: Comparison 1 * {[-2], [8], 3, 9, 0, 1, 7, 6} * Second trip: Worst comparison 2 * {-2, [3], [8], 9, 0, 1, 7, 6} * Third trip: Worst comparison 3 * {-2, 3, 8, 9, 0, 1, 7, 6} * four times: Worst comparison 4 * {-2, 3, 8, 0, 9, 1, 7, 6} * {-2, 3, 0, [8], [9], 1, 7, 6} * {-2, 0, [3], [8], [9], 1, 7, 6} * five times: Worst comparison 5 * {-2, 0, 3, 8, 1, [9], 7, 6} * {-2, 0, 3, 1, [8], [9], 7, 6} * {-2, 0, 1, [3], [8], [9], 7, 6} * Sixth trip: Worst comparison 6 * {-2, 0, 1, 3, 8, 7, [9], 6} * {-2, 0, 1, 3, 7, [8], [9], 6} * Seventh trip: Worst comparison 7 * {-2, 0, 1, 3, 7, 8, 6, [9]} * {-2, 0, 1, 3, 7, 6, [8], [9]} * {-2, 0, 1, 3, 6, [7], [8], [9]} * Number of comparisons: * 1+2+ .... + (n-1) = (n-1) * N/2 = O (n^2) *----------------------------------* {-2, 0, 1, 3, 6, 7, 8, 9} * @p Aram Arr */public static void Insertsort (int[] arr) {for (int i = 1; i < arr.length; i++) { for (int j = i; j > 0; j--) {if (Arr[j] < arr[j-1]) {swap (arr, J, J-1); } else {break; }}}} private static void Swap (int[] arr, int i, int j) {/*int tmp = arr[i]; Arr[i] = Arr[j]; ARR[J] = tmp;*/Arr[i] = arr[i] ^ arr[j]; ARR[J] = Arr[i] ^ arr[j]; Arr[i] = Arr[i] ^ arr[j]; }}
Test
排序前:[8, -2, 3, 9, 0, 1, 7, 6]排序后:[-2, 0, 1, 3, 6, 7, 8, 9]
Analysis of time complexity
1.时间复杂度为:O(n^2)2.插入排序是稳定排序法
Data structure and algorithms-insertion sort (Java implementation)