zoukankan      html  css  js  c++  java
  • acwing785. 快速排序

    给定你一个长度为 n 的整数数列。
    请你使用快速排序对这个数列按照从小到大进行排序。
    并将排好序的数列按顺序输出。

    输入格式

    输入共两行,第一行包含整数 n。
    第二行包含 n 个整数(所有整数均在 1∼10^9 范围内),表示整个数列。

    输出格式

    输出共一行,包含 n 个整数,表示排好序的数列。

    数据范围

    1≤n≤100000

    输入样例:

    5
    3 1 2 4 5
    

    输出样例:

    1 2 3 4 5
    

    方法一:

    写了好几个版本都超时了,一个可能是pivot没取随机值,第二个可能是把partition拆出来写了而且写得比较烂,增加了调用和执行时间吧,只能看看别人的写法

    #include <bits/stdc++.h>
    using namespace std;
    int n;
    int nums[100010];
    
    void quick_sort(int nums[], int low, int high) {
        if (low >= high) return;
    
        int p = rand() % (high-low+1) + low; // 取随机pivot
    
        int pivot = nums[p], i = low - 1, j = high + 1;
        while (i < j) {
            do i++; while (nums[i] < pivot);
            do j--; while (nums[j] > pivot);
            if (i < j) swap(nums[i], nums[j]);
        }
    
        quick_sort(nums, low, j);
        quick_sort(nums, j+1, high);
    }
    
    int main() {
        srand((int)time(0));
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
            scanf("%d", &nums[i]);
        
        quick_sort(nums, 0, n-1);
    
        for (int i = 0; i < n; i++)
            printf("%d ", nums[i]);
    }
    
  • 相关阅读:
    Python 集合 深浅copy
    python基础(基础数据类型)
    python基础一
    Asp.net获取网站绝对路径的几种方法
    Ajax请求被缓存的几种处理方式
    说说字符编码
    linux学习记录
    mysql基础
    【Android开发入门】关于ListView中按钮监听器设置的解决方案
    线程同步小结
  • 原文地址:https://www.cnblogs.com/nosae/p/15809099.html
Copyright © 2011-2022 走看看