快速排序
思路很简单 找一个基数,让左边的小于等于基数,右边的大于等于基数
#include <cstdio> #include <iostream> #include <set> #include <map> #include <stack> #include <queue> #include <cstring> #include <string> #include <sstream> #include <cmath> #include <cstdlib> #include <algorithm> #define sf scanf #define pf printf #define fp(x) freopen((x), "r", stdin) typedef long long ll; using namespace std; void pri1(int arr[], int start, int end) { while (start<=end) pf("%d ", arr[start++]); pf("\n"); } void pri2(int **arr, int start1, int end1, int start2, int end2) { for (int i=start1; i<=end1; i++) { for (int j=start2; j<=end2; ++j) { pf("%d ", arr[i][j]); } pf("\n"); } } void _qsort(int arr[], int left, int right) // 下标[a,b] { if (left >= right) return ; int tmp,i,j,tt; tmp = arr[(left+right)/2]; //实现“随机取基数” arr[(left+right)/2] = arr[left]; arr[left] = tmp; i = left; j = right; while (i < j) { while (i < j && tmp <arr[j]) j--; while (i < j && tmp>=arr[i]) i++; if (i < j) { tt = arr[i]; arr[i] = arr[j]; arr[j] = tt; } } arr[left] = arr[i]; arr[i] = tmp; _qsort(arr, left, i-1); _qsort(arr, i+1, right); } int main() { // int arr[] = {1, 8, 11, 5, 9, 2, 4, 6, 77, 111}; // int arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // int arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; // int arr[] = {1, 2, 1, 2, 1, 1, 1, 1, 1, 1}; // int arr[] = {1, 2, 1, 1, 1, 1, 1, 1, 1, 1}; _qsort(arr, 0, 9); pri1(arr, 0, 9); return 0; }