用js把数组转置、冒泡排序、插入排序包装成函数,要求排序函数能够选择升序或降序,
时间: 2023-04-07 11:04:53 浏览: 117
好的,这是一个技术问题,我可以回答。以下是三个函数的代码:
// 数组转置函数
function transpose(arr) {
return arr[0].map((col, i) => arr.map(row => row[i]));
}
// 冒泡排序函数
function bubbleSort(arr, order = 'asc') {
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - i - 1; j++) {
if ((order === 'asc' && arr[j] > arr[j + 1]) || (order === 'desc' && arr[j] < arr[j + 1])) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// 插入排序函数
function insertionSort(arr, order = 'asc') {
const len = arr.length;
for (let i = 1; i < len; i++) {
let j = i - 1;
const temp = arr[i];
while (j >= 0 && ((order === 'asc' && arr[j] > temp) || (order === 'desc' && arr[j] < temp))) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
return arr;
}
以上三个函数都接受一个数组作为参数,并且可以选择升序或降序排序。其中,transpose函数将二维数组转置,bubbleSort函数实现冒泡排序,insertionSort函数实现插入排序。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)