排序數組
給定一個整數數組 nums
,將該數組升序排列。
示例 1:
輸入:[5,2,3,1] 輸出:[1,2,3,5]
示例 2:
輸入:[5,1,1,2,0,0] 輸出:[0,0,1,1,2,5]
提示:
1 <= A.length <= 10000
-50000 <= A[i] <= 50000
1 class Solution { 2 public: 3 int LOW;//原始數組的左邊界 4 int HIGH;//原始數組的右邊界 5 vector<int> num;//原始數組復制后用來操作的新數組 6 int Partition(int low,int high){//尋找分界線下標 7 int temp = num[low];//在原始數組中隨機取一個數出來,留出一個空位置 8 while(low < high){ 9 while(low<high&&num[high] >= temp)//右邊的數要大於等於原來空位置上的數則,右邊界左移 10 --high; 11 num[low] = num[high];//把右邊第一個小於那個原來空位置上的數放到空位置上去,騰出了一個新的空位置 12 while(low<high&&num[low] <= temp)//左邊的數要小於等於原來空位置上的數則,左邊界右移 13 ++low; 14 num[high] = num[low];//把左邊第一個大於那個原來空位置上的數放到新的空位置上去,騰出了一個新的空位置 15 }//此時,以low下標為分界線,low的左邊的數都比隨機取出的數temp要小,low的右邊的數都比隨機取出來的數temp要大 16 num[low] = temp;//把隨機取出來的數放到分界線下標的空位置上去 17 return low;//返回分解線的下標 18 } 19 void quickSort(int low,int high) { 20 if(low < high){ 21 int key = Partition(low,high);//將數組分為兩部分
22 quickSort(low,key - 1);//將前半部分再進行快排 23 quickSort(key + 1,high);//將后半部分再進行快排 24 } 25 } 26 vector<int> sortArray(vector<int>& nums) {//入口函數 27 LOW = 0; 28 HIGH = nums.size() - 1; 29 num = nums; 30 quickSort(LOW,HIGH); 31 return num; 32 } 33 };