1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| var arr = [1,5,25,7,55,21,45,2,3,64,135,333,7882]
function quickSort(arr){ if(arr.length < 2) return arr; //如果长度小于2 直接返回 let left = 0, right = arr.length - 1; while(left < right) { while(arr[right] > a[0] && left < right){ // 找出右边比a[0]小的 right = right - 1 } while(arr[left] <= a[0] && left < right){ // 找出右边比a[0]大的 left++; } if(left == right){ let mid = arr[right]; arr[right] = arr[0]; arr[0] = mid; break; } let tmp = arr[right] arr[right] = arr[left] arr[left] = tmp } return quickSort(arr.slice(0,left)).concat(arr.slice(left,right+1)).concat(quickSort(arr.slice(right+1))) } console.log(quickSort(arr))
|