912. 排序数组(排序练手 )
给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 10
归并排序
class Solution: def sortArray(self, nums: List[int]) -> List[int]: def merge(nums,aux,l,mid,r): i = l j = mid+1 k = l while i <= mid and j <= r: if aux[i] > aux[j]: nums[k] = aux[i] i+=1 k+=1 else: nums[k] = aux[j] j+=1 k+=1 while i <= mid : nums[k] = aux[i] i+=1 k+=1 while j <= r: nums[k] = aux[j] j+=1 k+=1 aux[l:r+1] = nums[l:r+1] def m_sort(nums,aux,l,r): if l>=r: return mid = l + (r-l)//2 m_sort(nums,aux,l,mid) m_sort(nums,aux,mid+1,r) merge(nums,aux,l,mid,r) m_sort(nums,nums.copy(),0,len(nums)-1) return nums[::-1]
快速排序
import random class Solution: def sortArray(self, nums: List[int]) -> List[int]: def partation(nums,i,j): pivot = nums[i] l = i+1 r = j while l <= r: if nums[l]<pivot<nums[r]: nums[l],nums[r] = nums[r],nums[l] l+=1 r-=1 if not nums[l] < pivot: l+=1 if not pivot < nums[r]: r-=1 nums[r],nums[i] = nums[i],nums[r] return r def quick_sort(nums,i,j): if i >= j: return k = partation(nums,i,j) quick_sort(nums,i,k-1) quick_sort(nums,k+1,j) random.shuffle(nums) quick_sort(nums,0,len(nums)-1) return nums[::-1]
堆排序
class Solution: def sortArray(self, nums: List[int]) -> List[int]: def maxHepify(arr, i, end): # 大顶堆 j = 2*i + 1 # j为i的左子节点【建堆时下标0表示堆顶】 while j <= end: # 自上而下进行调整 if j+1 <= end and arr[j+1] > arr[j]: # i的左右子节点分别为j和j+1 j += 1 # 取两者之间的较大者 if arr[i] < arr[j]: # 若i指示的元素小于其子节点中的较大者 arr[i], arr[j] = arr[j], arr[i] # 交换i和j的元素,并继续往下判断 i = j # 往下走:i调整为其子节点j j = 2*i + 1 # j调整为i的左子节点 else: # 否则,结束调整 break n = len(nums) # 建堆【大顶堆】 for i in range(n//2)[::-1]: # 从第一个非叶子节点n//2-1开始依次往上进行建堆的调整 maxHepify(nums, i, n-1) # 排序:依次将堆顶元素(当前最大值)放置到尾部,并调整堆 for j in range(n)[::-1]: nums[0], nums[j] = nums[j], nums[0] # 堆顶元素(当前最大值)放置到尾部j maxHepify(nums, 0, j-1) # j-1变成尾部,并从堆顶0开始调整堆 return nums