快速排序算法

分治法
O(nlogn)

pivot 基准元素
选定了基准元素以后,我们要做的就是把其他元素当中小于基准元素的都移动到基准元素一边,大于基准元素的都移动到基准元素另一边。
具体如何实现呢?有两种方法:
1.挖坑法
2.指针交换法


用递归, 就是用空间换取时间

void quickSort(int[] arr, int startIndex, int endIndex) {

    if (startIndex >= endIndex) {
      return;
    }

    int pivotIndex = partition(arr, startIndex, endIndex);

    quickSort(arr, startIndex, pivotIndex - 1);
    quickSort(arr, startIndex + 1, endIndex);
}


private int partition(int [] arr, int startIndex, int endIndex){

  int pivot = arr[startIndex];
  int left = startIndex;
  int left = endIndex;

  while (left != right) {

    while(left < right && arr[right] > pivot) {
      right--;
    }
    while(left < right && arr[left] <= pivot) {
      left++;
    }
    if(left < right) {
      swap(left, right);
    }
  }
  //pivot和指针重合点交换
  swap(left, pivot)
  return left;
}

 

发布了247 篇原创文章 · 获赞 24 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章