JavaScript 插入排序法
Posted 乱舞春秋__
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 插入排序法相关的知识,希望对你有一定的参考价值。
函数封装如下:
1.从小到大排序
function insertionSort(array) {
if (!Array.isArray(array)) {
return;
}
if (array.length <= 1) {
return array;
}
var currentValue;
var preIndex;
for (var i = 1; i < array.length; i++) {
currentValue = array[i];
preIndex = i - 1;
while (preIndex >= 0 && array[preIndex] > currentValue) {
array[preIndex + 1] = array[preIndex];
preIndex--;
}
array[preIndex + 1] = currentValue;
}
}
2.从大到小排序
function insertionSort(array) {
if (!Array.isArray(array)) {
return;
}
if (array.length <= 1) {
return array;
}
var currentValue;
var preIndex;
for (var i = 1; i < array.length; i++) {
currentValue = array[i];
preIndex = i - 1;
while (preIndex >= 0 && array[preIndex] < currentValue) {
array[preIndex + 1] = array[preIndex];
preIndex--;
}
array[preIndex + 1] = currentValue;
}
}
示例:
(1)将一个数组从小到大排序
var arr = [1, 2, 6, 3, 6, 8, 5, 3, 6, 8, 8, 5, 3];
function insertionSort(array) {
if (!Array.isArray(array)) {
return;
}
if (array.length <= 1) {
return array;
}
var currentValue;
var preIndex;
for (var i = 1; i < array.length; i++) {
currentValue = array[i];
preIndex = i - 1;
while (preIndex >= 0 && array[preIndex] > currentValue) {
array[preIndex + 1] = array[preIndex];
preIndex--;
}
array[preIndex + 1] = currentValue;
}
}
insertionSort(arr);
console.log(arr);
控制台输出:
(2)将一个数组从大到小排序
var arr = [1, 2, 6, 3, 6, 8, 5, 3, 6, 8, 8, 5, 3];
function insertionSort(array) {
if (!Array.isArray(array)) {
return;
}
if (array.length <= 1) {
return array;
}
var currentValue;
var preIndex;
for (var i = 1; i < array.length; i++) {
currentValue = array[i];
preIndex = i - 1;
while (preIndex >= 0 && array[preIndex] < currentValue) {
array[preIndex + 1] = array[preIndex];
preIndex--;
}
array[preIndex + 1] = currentValue;
}
}
insertionSort(arr);
console.log(arr);
控制台输出:
以上是关于JavaScript 插入排序法的主要内容,如果未能解决你的问题,请参考以下文章