快速排序算法模板+内置函数

思想:
  1. 确定分界点
  2. 调整区间 ,小于分界点的在左边区间,大于分界点在右边区间。
  3. 递归处理左右两边。
void quick_sort(int q[], int l, int r)
{
    if (l >= r) return;

    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j)
    {
        do i ++ ; while (q[i] < x);
        do j -- ; while (q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }
    quick_sort(q, l, j), quick_sort(q, j + 1, r);
}

但是呢,有内置函数也就是快排

C++和Java内置的排序函数分别是`std::sort()`和`Arrays.sort()`。

1. C++中的`std::sort()`函数:
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> arr = {5, 3, 1, 4, 2};
    std::sort(arr.begin(), arr.end());
    return 0;
}
```

2. Java中的`Arrays.sort()`函数:
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 3, 1, 4, 2};
        Arrays.sort(arr);
    }
}

 

posted @ 2023-10-20 21:12  阿飞藏泪  阅读(13)  评论(0编辑  收藏  举报
1 2 3
4