hello-algo/codes/typescript/chapter_sorting/insertion_sort.ts

28 lines
729 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: quick_sort.ts
* Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com)
*/
/* 插入排序 */
function insertionSort(nums: number[]): void {
// 外循环base = nums[1], nums[2], ..., nums[n-1]
for (let i = 1; i < nums.length; i++) {
const base = nums[i];
let j = i - 1;
// 内循环:将 base 插入到左边的正确位置
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // 1. 将 nums[j] 向右移动一位
j--;
}
nums[j + 1] = base; // 2. 将 base 赋值到正确位置
}
}
/* Driver Code */
const nums = [4, 1, 3, 1, 5, 2];
insertionSort(nums);
console.log('排序后数组 nums =', nums);
export {};