function insertionSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {//等价于 (array instanceof Array) 判断是否为数组
var len = array.length;
if (len <= 1) {//数组只有0个或者一个元素时,不用排序
return array;
}
for (var i = 1; i < len; i++)
{
var insertionElement = array[i];//取出一个新元素用作插入子数组
for (var j = 0; j < i ; j++) {//由0到i-1的子数组
if (array[j] < insertionElement)//元素大于,不移动
continue;
else if (array[j] == insertionElement) {//元素等于,不交换
for (var move = i; move > j; move--) {//子数组向后移动1位(如果有链表就可以直接链上,js没有链表)
array[move] = array[move - 1];//注意:数组移动要注意顺序
}
break;
}
else {//元素小于时交换
for (var move = i; move > j; move--) {//子数组向后移动1位
array[move] = array[move - 1];
}
array[j] = insertionElement;
break;
}
}
}
return array;
}
else {//不是数组
return 'Not an Array!';
}
} function bubbleSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {//等价于 (array instanceof Array) 判断是否为数组
var len = array.length;
if (len <= 1) {//数组只有0个或者一个元素时,不用排序
return array;
}
for (var i = 0; i < len - 1; i++) {
for (var j = i + 1; j < len; j++) {
if (array[j] < array[i]) {//最小的值上浮
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
} return array;
}
else {//不是数组
return 'Not an Array!';
}
} console.log(insertionSort(["a", "cd", "ee", "hello", "this", "hey", "e", "go", "what", "yo", "foo"]));
console.log(bubbleSort(["a", "cd", "ee", "hello", "this", "hey", "e", "go", "what", "yo", "foo"]));