1. 程式人生 > >464 整數排序Ⅱ

464 整數排序Ⅱ

rip post render AI pub type detail AS ac代碼

原題網址: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++總結

464 整數排序Ⅱ