function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
return arr;
}
function InsertSort(array) {
for (let i = 1; i < array.length; i++) {
let t = array[i];
for (let j = i-1; j>=0; j--) {
if ( array[j] > t) {
[array[j], array[j + 1]] = [array[j + 1], array[j]]
}
}
}
return array
}
function InsertCustomSort(array) {
for (let i = 1; i < array.length; i++) {
let t = array[i]
for (let j = 0; j<= i-1; j++) {
if (array[j]>t) {
array.splice(j,0,...array.splice(i,1))
break;
}
}
}
return array
}
function quickSort(arr){
if (arr.length<=1) {
return arr
}
let l = []
let r = []
let a = arr[0]
for (let i = 1; i < arr.length; i++) {
if (arr[i]<a) {
l.push(arr[i])
}else {
r.push(arr[i])
}
}
return quickSort(l).concat([a]).concat(quickSort(r))
}
var arr = [];
for (let i = 0; i < 10000; i++) {
arr.push( parseInt(Math.random()*10000))
}
function timeCreent() {
return + new Date()
}
let t1 = timeCreent()
var arrSorted1 = InsertSort(JSON.parse(JSON.stringify(arr)));
let t2= timeCreent()
console.log(arrSorted1,'InsertSort');
console.log(t2-t1,'t2-t1');
var arrSorted2 = InsertCustomSort(JSON.parse(JSON.stringify(arr)));
let t3= timeCreent()
console.log(arrSorted2,'InsertCustomSort');
console.log(t3-t2,'t3-t2');
var arrSorted3 = bubbleSort(JSON.parse(JSON.stringify(arr)));
let t4= timeCreent()
console.log(arrSorted3,'bubbleSort');
console.log(t4-t3,'t4-t3');
var arrSorted4 = quickSort(JSON.parse(JSON.stringify(arr)));
let t5= timeCreent()
console.log(arrSorted4,'quickSort');
console.log(t5-t4,'t5-t4');
console.log(arr,'arr');
冒泡 快排 插入对比
最新推荐文章于 2024-11-12 11:19:19 发布