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