function sort(arr) {
let len = arr.length; // 最后一个元素
let count = 0;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i - 1; j++) {
count++;
if (arr[j] > arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
console.log(count);
return arr;
}
sort([3,2,1,4,6,7,8,9,0,5]) // 45
function sort(arr) {
let len = arr.length; // 最后一个元素
let count = 0;
let laseIndex = 0
let sort_border = len - 1;
for (let i = 0; i < len; i++) {
let is_sort = true;
for (let j = 0; j < sort_border; j++) {
count++;
if (arr[j] < arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
is_sort = false;
laseIndex = j;
}
}
sort_border = laseIndex;
if (is_sort) {
break;
}
}
console.log(count);
return arr;
}
sort([3,2,1,4,6,7,8,9,0,5]) // 40
鸡尾酒排序
function sort(arr) {
let len = arr.length; // 最后一个元素
let count = 0;
for (let i = 0; i < len; i++) {
let is_sort = true;
for (let j = 0; j < len - i - 1; j++) {
count++;
if (arr[j] > arr[j + 1]) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
is_sort = false;
}
}
if (is_sort) {
break;
}
is_sort = true;
for (let j = len - i - 1; j > 0; j--) {
count++;
if (arr[j] < arr[j - 1]) {
const temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
is_sort = false;
}
}
if (is_sort) {
break;
}
}
console.log(count);
return arr;
}
sort([1,2,3,4,5,6,7,8,9,0]) // 26