Several common algorithms

1. Bubble sort

 Sort an array by comparing and exchanging adjacent two elements

function sort1(arr){

for(let i = 0; i < arr.length - 1; i++){

   for(let j = 0; j<arr.length - i; j++){

       if(arr[i]>arr[j+1]){

         let temp = arr[i]

         arr[i] = arr[j]

         arr[j] = temp

         }

     }

  }

return arr;

}

2. Selection sort 

Each time the smallest element is selected from the unsorted array, placed at the end of the sorted array, and this process is repeated until the array is complete

function sort2(arr){
           const n=arr.length
           for(let i=0;i<n-1;i++){
               let minIndex=i
               for (let j=i+1;j<n;j++){
                   if(arr[j]<arr[minIndex]){
                       minIndex=j
                   }
               }
               if(minIndex!=i){
                   [arr[i],arr[minIndex]]=[arr[minIndex],arr[i]]
               }
            }
           return arr;
}

3. Insertion sort

Divide the array into sorted and unsorted parts. Initially, the sorted part contains only one element. Each time an element is selected from the unsorted part and inserted into the correct position of the sorted part, until all elements are sorted

 function sort3(arr){
          const n = arr.length
          for(let i = 1;i<n;i++){
              const key = arr[i]
              let j = i-1;
              while(j >=0&&arr[j]>key){
                  arr[j+1] = arr[i]
                  j--;
              }
              arr[j+1]=key
          }
          return arr;
      }

4. Quick Sort

Select a reference element, divide the array into two parts, some elements are smaller than the reference element, and the other part of the elements are larger than the reference element, recursively sort the two parts

function sort4(arr,left,right){
         if(left>right){
             const pivotIndex = getpivotIndex(arr,left,right)
             sort4(arr,left,pivotIndex-1)
             sort4(arr,pivotIndex+1,right)
         }
         return arr
     }
     function getpivotIndex(arr,left,right){
         const pivot = arr[right]
         let i =left-1
         for(let j = left;j<right;j++){
             if(arr[j] <= pivot){
                 i++
                 [arr[i],arr[j]] = [arr[i],arr[j]]
             }
         }
         [arr[i+1],arr[right]] = [arr[right],arr[i+1]]
         return i + 1;     
     }

Guess you like

Origin blog.csdn.net/and_life/article/details/131068329