JavaScript sorting

Leetcode details

Bubble sort

const arr=[911.520.888.Awesome!.555.2323];
function bubbleSort(arr){
    let temp;
    for(let i=0; i<arr.length-1; i++){for(let j=0; j<arr.length-1-i; j++){if(arr[j]>arr[j+1]){
               temp=arr[j];
               arr[j]=arr[j+1];
               arr[j+1}=temp; }}}return arr;
}
Copy the code

Quick sort

let arr=[2.3.13.3.46.1]
function quickSort(arr){
  if(arr.length===1||arr.length===0) {return arr
  }
  let index=Math.floor(arr.length/2);
  let leftList=[],rightList=[];
  let currentItem=arr.splice(index,1);
  arr.forEach(element= >{
    if(element<=currentItem){
      leftList.push(element)
    }else{
      rightList.push(element)
    }
  });
  return quickSort(leftList).concat(currentItem).concat(quickSort(rightList))
}
console.log(quickSort(arr))
Copy the code

Selection sort

function chooseSort(arr){
    let minIndex = 0;
    let length = arr.length;
    for(let i=0; i<length-1; i++){ minIndex = i;for(letj=i; j<length; j++){if(arr[minIndex]>arr[j]){ minIndex = j; }}if(minIndex! ==i){ [arr[i],arr[minIndex]] = [arr[minIndex],arr[i]] } }return arr
}
Copy the code