javascript请写出三种排序的方法,实现对整arrays由小到小的排序
时间: 2024-05-12 16:20:35 浏览: 9
1. 冒泡排序
```javascript
function bubbleSort(arr){
let len = arr.length;
for(let i = 0; i < len - 1; i++){
for(let j = 0; j < len - 1 - i; j++){
if(arr[j] > arr[j+1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
let arr = [3, 2, 5, 1, 4];
console.log(bubbleSort(arr)); // [1, 2, 3, 4, 5]
```
2. 选择排序
```javascript
function selectionSort(arr){
let len = arr.length;
for(let i = 0; i < len - 1; i++){
let minIndex = i;
for(let j = i + 1; j < len; j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
if(minIndex !== i){
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
return arr;
}
let arr = [3, 2, 5, 1, 4];
console.log(selectionSort(arr)); // [1, 2, 3, 4, 5]
```
3. 插入排序
```javascript
function insertionSort(arr){
let len = arr.length;
for(let i = 1; i < len; i++){
let j = i;
while(j > 0 && arr[j] < arr[j-1]){
let temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
return arr;
}
let arr = [3, 2, 5, 1, 4];
console.log(insertionSort(arr)); // [1, 2, 3, 4, 5]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)