冒泡排序
<script>
let arr = [5,67,2,44,9,56,49]
// 冒泡(升序)
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]){
swap(arr,j,j+1);
}
}
}
return arr;
}
function swap(arr,a,b) {
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
arr = bubbleSort(arr);
console.log(arr);
</script>
选择
let arr = [5,67,2,44,9,56,49];
function selectionSort(arr){
const n = arr.length;
for (let i = 0; i < n - 1;i ++){
let minIndex = i;
for(let j = i + 1;j < n ; j++){
if (arr[j] < arr[minIndex]){
minIndex = j;
}
}
if (minIndex !== i) {
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
return arr;
}
console.log(selectionSort(arr));
插入排序
<script>
let arr = [5,67,2,44,9,56,49];
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
let current = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}
console.log(insertionSort(arr));
</script>