整数排序2

来源:互联网 发布:vb皮肤控件 skinsharp 编辑:程序博客网 时间:2024/05/29 14:06

问题描述:

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

解题思路:

运用了快速排序

实现代码:

class Solution {
public:
    /**
     * @param A an integer array
     * @return void
     */
    void sortIntegers2(vector<int>& A) {
        // Write your code here
        QuickSort(A,0,A.size()-1);
    }
    void QuickSort(vector<int>& A,int first,int end)
    {
        if(first<end) {
           int pivot=Partition(A,first,end);
            QuickSort(A,first,pivot-1);
            QuickSort(A,pivot+1,end);
        }
    }
    int Partition(vector<int>& A,int first,int end)
    {
        int i=first;
        int j=end;
        while(i<j)
       {
           while(i<j&&A[i]<=A[j]) j--;
           if(i<j){
               swap(A[i],A[j]);
               i++;
           }
           while(i<j&&A[i]<=A[j]) i++;
           if(i<j){
               swap(A[i],A[j]);
               j--;
           }
     }
     return i;
  }
};

感想:运用课本上的快速排序的算法就解决了。