Insertion Sort
Easy sorting · arrays
Description
Constraints
0 <= n <= 100000
Examples
Input: nums = [5,2,4,6,1,3]
Output: [1,2,3,4,5,6]
Hints (1)
- Grow a sorted prefix by inserting each next element into place.
Solutions
Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)
func insertionSort(nums []int) []int {
a := append([]int{}, nums...)
for i := 1; i < len(a); i++ {
key := a[i]
j := i - 1
for j >= 0 && a[j] > key {
a[j+1] = a[j]
j--
}
a[j+1] = key
}
return a
}
Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)
function insertionSort(nums) {
const a = [...nums];
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
return a;
}
Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)
function insertionSort($nums) {
for ($i = 1; $i < count($nums); $i++) {
$key = $nums[$i]; $j = $i - 1;
while ($j >= 0 && $nums[$j] > $key) { $nums[$j + 1] = $nums[$j]; $j--; }
$nums[$j + 1] = $key;
}
return $nums;
}
Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)
def insertionSort(nums):
a = list(nums)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)
function insertionSort(nums: number[]): number[] {
const a = [...nums];
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
return a;
}
Create a free account to submit solutions, track progress and save problems.
Create account