Quick Sort Solution

quick sort

You are given an array of integers of length n. Please use quick sort to sort this array from smallest to largest. And output the sorted array in order.

input format
The input consists of two lines, the first line contains the integer n

The second line contains n
  integers (all integers in the range 1-1e9) represent the entire sequence.

output format
The output is a total of one line, containing n integers representing the sorted sequence.

data range
1≤n≤100000
Input sample:
5
3 1 2 4 5
Sample output:
1 2 3 4 5

problem solving ideas 

1. The quick_sort function takes an array q, a left index l, and a right index r as input. If l >= r, the function returns immediately.

2. The function selects a pivot element x as the middle element between l and r.

3. The function initializes two pointers `i` and `j` to l-1 and r+1, respectively.

4. The function enters a loop that increments i until q[i] >= x, decrements j until q[j] <= x, and swaps q[i] and q[j] if i < j.

5. The function recursively calls quick_sort on the left subarray q[l...j] and the right subarray q[j+1...r].

6. In the main function, the code reads in an integer n, followed by n integers into the array q.

7. The code calls quick_sort on the entire array q.

8. The code prints out the sorted array q.

The time complexity of QuickSort is O(nlogn) on average, but can degrade to O(n^2) in the worst case. The space complexity of QuickSort is O(logn) on average, but can degrade to O(n) in the worst case.

#include <iostream>

using namespace std;

const int N = 10010;

int q[N];

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);
}

int main() {
    int n;
    cin >> n;

    for (int i = 0; i < n; i++) cin >> q[i];

    quick_sort(q, 0, n - 1);

    for (int i = 0; i < n; i++) cout << q[i] << " ";

    return 0;
}

Summary

for quicksort The core idea is to divide and conquer. Each time an intermediate value is found, the array is divided into left and right areas each time. Some areas are larger than a certain value, and the other area is smaller than a certain value, and then each part is recursively

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值