zoukankan      html  css  js  c++  java
  • 464 整数排序Ⅱ

    原题网址:https://www.lintcode.com/problem/sort-integers-ii/description

    描述

    给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。

    您在真实的面试中是否遇到过这个题?  

    样例

    给出 [3, 2, 1, 4, 5], 排序后的结果为 [1, 2, 3, 4, 5]

    标签
    排序
    快速排序
    归并排序
    思路1:用快排序,挖坑填数+分治法(递归)。
     
    AC代码:
    class Solution {
    public:
        /**
         * @param A: an integer array
         * @return: nothing
         */
        void sortIntegers2(vector<int> &A) {
            // write your code here
        int size=A.size();
        if (size==0)
        {
            return ;
        }
        qSort(A,0,size-1);
        }
        
        void qSort(vector<int> &A,int l,int r)
    {
        if (l>=r)
        {
            return ;
        }
        int x=A[l];//A[l]基准,也就是第一个坑;
        int i=l,j=r;
        while(i<j)
        {
            //从右向左找小于x的数,填入坑中;
            while(i<j&&A[j]>=x)
            {
                j--;
            }
            if (i<j)
            {
                A[i]=A[j];//A[j]填入坑中,j处形成新的坑;
                i++;
            }
            //从左向右找大于等于x的数,填入坑中;
            while(i<j&&A[i]<x)
            {
                i++;
            }
            if (i<j)
            {
                A[j]=A[i];//A[i]填入坑中,i处形成新的坑;
                j--;
            }
        }
        //循环结束时,i==j,将x填入坑中;
        A[i]=x;
        //递归;
        qSort(A,l,i-1);
        qSort(A,i+1,r);
    }
    };

    其他排序算法可参考:常见排序算法C++总结

  • 相关阅读:
    实验6:Mapreduce实例——WordCount
    暑期生活10
    暑期生活9
    暑期生活8
    暑期生活7
    暑期生活6
    暑期生活5
    暑期生活4
    暑期生活3
    暑期生活2
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9241204.html
Copyright © 2011-2022 走看看