【C++ 算法笔记】 Sort的六种方法 【二】Quick Sort

本文深入解析了快速排序算法的实现原理及代码实现,通过递归概念讲解如何选择枢轴点并进行数组划分,以达到最佳排序效果。文章还讨论了算法在不同情况下的运行时间复杂度。

IMPORTANT

THIS IS NOTE I MADE WHEN STUDY C++ ALGORITHM
THIS NOTE WOULD ONLY HELP U SPEND LESS TIME ON UNDERSTNDING THE ALGORITHM AND CODE IMPLEMENTATION
ALL WORDS IN " " ARE DIRECTLY REFERENCE
ALL CODE IMPLEMATATION ARE DIRECTLY REFERENCE
PLEASE CLICK THE LINK BELOW TO READ ORIGINAL BOOK AND INSTRUCTION

https://cathyatseneca.gitbook.io/data-strutures-and-algorithms/


Quick Sort

Part A:

template <class TYPE>
void QuickSort(vector<TYPE>& arr){
  QuickSort(arr,0,arr.size()-1);
}

Part B:

template <class TYPE>
void QuickSort(vector<TYPE>& arr, int left, int right){
  if(right-left <=3){
    InsertionSort(arr,left,right);
  }
  else{
    int pivotpt=right;
    int i=left;
    int j=right-1;
    TYPE pivot=arr[pivotpt];
    while(i<j){
      while(arr[i]<pivot) i++;
      while(arr[j]>pivot) j--;
      if(i<j)
        swap(arr[i++],arr[j--]);
    }
    swap(arr[i],arr[pivotpt]);
    QuickSort(arr,left,i-1);
    QuickSort(arr,i+1,right);
  }
}
  • sort with “jumping”
  • run time depends on different situation:
    • the best situation: O(nlogn)
    • the worst situation is: O(n^2)
  • (index might change if there are some data with same value)?
  • Recursice concept is needed

TO implement this, a pivot point is needed.
PArt A create a new prototype for the function in partB.
In part B,
A pivot point is decleared with the most right value in the array.
In the first while-loop ensures i and j will meet each other,
and this is exact location of pivot point;
the following two while-loop finds the number smaller than pivot and larger than pivot respectively;
when those two numbers are finded,
switch their positions and continue.
Placed the pivot point in correct location represent the end of the firsr round,
repeat above step recursively by dividing this array into two pieces,
pivot uses to indetify the break.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值