题解 | #快速排序#
快速排序
https://www.nowcoder.com/practice/38da660199d0400580ac3905c05f5bd6
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> /* 填写样式 */ </style> </head> <body> <!-- 填写标签 --> <script type="text/javascript"> // 填写JavaScript const _quickSort = array => { // 快排 从小到大 if (array.length < 2) return array; let middleIndex = Math.floor(array.length / 2); // 该下标所在元素(可能重复)第一个不用判断,不用进入遍历,取出 let middle = array.splice(middleIndex, 1)[0]; let leftArray = []; let rightArray = []; for (let i = 0; i < array.length; i++) { if (array[i] < middle) { leftArray.push(array[i]); }else { rightArray.push(array[i]); } } return [..._quickSort(leftArray), middle,..._quickSort(rightArray)] } </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> /* 填写样式 */ </style> </head> <body> <!-- 填写标签 --> <script type="text/javascript"> // 填写JavaScript const _quickSort = array => { // 快排 return array.sort((a, b) => (a - b)); } </script> </body> </html>