快速排序算法实现(递归)

使用Golang实现的快速排序算法

func QuickSort(src []int) {
 if len(src) <= 1 {
      return
 }
 
 midV := src[0]
 length := len(src)
 leftIndex := 1
 rightIndex := length - 1
 for leftIndex <= rightIndex {
      for leftIndex < length && src[leftIndex] <= midV {
         leftIndex++
      }
      for rightIndex > 0 && src[rightIndex] > midV {
         rightIndex--
      }
      //swap
      if leftIndex < rightIndex {
         src[leftIndex], src[rightIndex] = src[rightIndex], src[leftIndex]
      }
   }
   
   //recursion sort sub src
   if rightIndex > 0 {
      src[0], src[rightIndex] = src[rightIndex], src[0]
   }
   
   // 给左子集排序
   if rightIndex > 0 {
      QuickSort(src[:rightIndex])
   }
   
   // 给右子集排序
   if rightIndex < length-2 {
      QuickSort(src[rightIndex+1:])
   }
}

你可能感兴趣的