Skip to content

快速排序-C++ #30

@hubvue

Description

@hubvue

快排C++版

#include <iostream>

using namespace std;
void quick_sort(int arr[], int l, int r);
int main()
{
  int arr[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
  int len = sizeof(arr) / sizeof(int);
  quick_sort(arr, 0, len - 1);
  for (int i = 0; i < len; i++)
  {
    cout << arr[i] << ',';
  }
  cout << endl;
  return 0;
}
// 快速排序
void quick_sort(int arr[], int l, int r)
{
  if (l < r)
  {
    int left = l, right = r, target = arr[left];

    while (left < right)
    {
      while (left < right && arr[right] > target)
      {
        right--;
      }
      if (left < right)
      {
        arr[left] = arr[right];
      }
      while (left < right && arr[left] < target)
      {
        left++;
      }
      if (left < right)
      {
        arr[right] = arr[left];
      }
    }
    arr[left] = target;
    quick_sort(arr, l, left - 1);
    quick_sort(arr, left + 1, r);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions