1
0

quick_sort.cpp 877 B

12345678910111213141516171819202122232425262728293031323334
  1. // 快速排序
  2. #include <iostream>
  3. #include <algorithm>
  4. using namespace std;
  5. void quicksort(int* arr, int left, int right);
  6. int main() {
  7. int n;
  8. cin >> n;
  9. int* arr = new int[n];
  10. for (int i = 0; i < n; ++i)
  11. cin >> arr[i];
  12. quicksort(arr, 0, n-1);
  13. for (int i = 0; i < n; ++i)
  14. cout << arr[i] << " ";
  15. delete [] arr;
  16. return 0;
  17. }
  18. void quicksort(int* arr, int left, int right) {
  19. if (left >= right) return;
  20. int i = left, j = right, base = arr[left]; // 以最右元素为基准 base = arr[right]
  21. while (i < j) {
  22. while (arr[j] >= base && i < j) --j; // 从基准数相反方向开始调换
  23. while (arr[i] <= base && i < j) ++i; // 这两行对调
  24. if (i < j) swap(arr[i], arr[j]);
  25. }
  26. arr[left] = arr[i]; // arr[right] = arr[i]
  27. arr[i] = base;
  28. quicksort(arr, left, i-1);
  29. quicksort(arr, i+1, right);
  30. }