排序算法

  1. 快速排序
    1. 插入排序

快速排序

function sort(nums, l, r) {
   if(r - l <= 0) return
   let pivot = partition1(nums, l, r)
   console.log('pivot', pivot)
   // left
   sort(nums, l, pivot -1)
   // right
   sort(nums, pivot + 1, r)
   return nums
}

function partition(nums,l,r) {
   // 中心位置
   let center = l
   // 指针
   let compare = r
   while(center != compare) {
       // 在右边移动指针时
       if(center < compare) {
          if(nums[center] > nums[compare]) {
             let temp = nums[center]
             nums[center] = nums[compare]
             nums[compare] = temp
             let num = compare
             compare = center
             center = num
             compare++
             continue
          }
          compare--
       }
       // 在左边移动指针时
       else {
           if(nums[center] < nums[compare]) {
              let temp = nums[center]
              nums[center] = nums[compare]
              nums[compare] = temp
              let num = compare
              compare = center
              center = num
              compare--
              continue
          }
          compare++    
       }
   }
   console.log(nums)
   return center
 }

 function partition1 (nums,l,r) {
    // 保存基准值
    let pivot = nums[l]
    while(l!=r) {
       while(r > l && nums[r] >= pivot) {
         r--
       }
       nums[l] = nums[r]
       while(r > l && nums[l] <= pivot) {
         l++
       }
       nums[r] = nums[l]
    }
    nums[l] = pivot
    return l
 }

 console.log(sort([45,23,55,12,4,88,1,2,4], 0, 8))

插入排序

function sort(nums) {
   for(let i = 0; i < nums.length; i++) {
      // 插入的数
      let insert = nums[i]
      //j 为排序列表长度
      let j = i -1
      for(j ; j >= 0; j--) {
         if(insert < nums[j]) {
            // insert往前挪
            nums[j + 1] = nums[j]
            nums[j] = insert
         }
      }
   }
   return nums
}

function sort2(nums) {
   for(let i = 0; i < nums.length; i++) {
      // 插入的数
      let insert = nums[i]
      //j 为已排序列表长度
      let j = i -1
      while(j>= 0 && insert < nums[j]) {
            nums[j + 1] = nums[j]
            j--z
      }
      nums[j + 1] = insert
   }
   return nums
}




 console.log(sort([45,23,55,12,4,88,1,2,4]))



转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1249118795@qq.com