快速排序算法

分治法
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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章