Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

98.快速排序 #98

Open
webVueBlog opened this issue Mar 3, 2023 · 0 comments
Open

98.快速排序 #98

webVueBlog opened this issue Mar 3, 2023 · 0 comments

Comments

@webVueBlog
Copy link
Member

// 原理
// 分治的思想
// 先随机选出一个元素作为基准
// 比基准点小的放在左边
// 比基准点大的放在右边
// 时间复杂度:O(nlogn)

/**
 * 最简单的快速排序
 * @param {any[]} arr
 */
function quickSort(arr) {
 if (arr.length < 2) {
  return arr.slice();
 }
 
 // 随机找到基准点
 const pivot = arr[Math.floor(Math.random() * arr.length)];
 
 let left = [];
 let middle = [];
 let right = [];
 
 for (let index = 0; index < arr.length; index++) {
  const value = arr[index];
  
  if (value  < pivot) {
   letf.push(value);
  }
 
  if (value === pivot) {
   middle.push(value);
  }
 
  if (value > pivot) {
   right.push(value);
  }
 }
  
 // 递归进行
 return quickSort(left).concat(middle, quickSort(right));
}

let arr = [23,45,3,232];
console.log( quickSort(arr) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant