Insertion Sort

本文详细介绍了插入排序算法的工作原理及其实现过程。通过示例展示了如何将数组中的元素按顺序排列,并提供了具体的Java代码实现。此外,还分析了该算法的时间复杂度为O(n^2),空间复杂度为O(1),并指出它是一种原地排序算法。

(referrence: GeeksforGeeks)

Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.

Insertion Sort

Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]

Example: 
12, 11, 13, 5, 6

Let us loop for i = 1 (second element of the array) to 5 (Size of input array)

i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6

i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6

i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current position.
5, 11, 12, 13, 6

i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current position.
5, 6, 11, 12, 13

 1 class Solution {
 2     public static void insertionSort(int[] nums) {
 3         for (int i = 1; i < nums.length; i++) {
 4             key = nums[i];
 5             int j = i - 1;
 6 
 7             while (j >= 0 && nums[j] > key) {
 8                 nums[j + 1] = arr[j]
 9                 j--;
10             }
11             nums[j + 1] = key;
12         }
13     }
14 }

Time complexity O(n^2), space cost O(1), and it's in-place sorting.

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4856695.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值