选择排序(Selection Sort)
选择排序(Selection Sort)
选择排序也是一种简单直观的排序算法。它的工作原理是:第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后再从剩余的元素中寻找最小(或最大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素排完。
示例
3
5
7
8
4
1
6
9
2
点我排序
vue
<script setup lang="ts">
import {reactive} from "vue";
const selectionSorttList = reactive({
selectionSorttList:[3,5,7,8,4,1,6,9,0]
})
const selectionSorttClick= ()=>{
selectionSort(selectionSorttList.selectionSorttList)
}
function selectionSort(arr) {
let 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;
}
}
// 交换元素
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
return arr;
}
</script>
<template>
<p>{{JSON.stringify(selectionSorttList.selectionSorttList)}}</p>
<h4 @click="selectionSorttClick">点我排序</h4>
</template>
<style scoped lang="scss">
</style>