sort

1. quickSort

 1 import random
 2 class Solution:
 3     def partition(self,nums,left,right):
 4         idx=random.randint(left,right)      # 闭区间
 5         pivot=nums[idx]
 6 
 7         nums[idx],nums[right]=nums[right],nums[idx]
 8         
 9         pos=left
10         for i in range(left,right):
11             if(nums[i]<pivot):
12                 nums[i],nums[pos]=nums[pos],nums[i]
13                 pos+=1
14         
15         nums[pos],nums[right]=nums[right],nums[pos]
16         return pos
17 
18     def quickSort(self,nums):
19         if(len(nums)==1):
20             return nums
21         left,right=0,len(nums)-1
22 
23         return self.quickSort_helper(nums,left,right)
24 
25     def quickSort_helper(self,nums,left,right):
26         if(left<right):
27             pos=self.partition(nums,left,right)
28             self.quickSort_helper(nums,left,pos-1)
29             self.quickSort_helper(nums,pos+1,right)
30         
31         return nums
32 
33 
34 nums=[5,2,34,21]
35 print(Solution().quickSort(nums))

 

 

 

2. mergeSort

 

 1 class Solution2:
 2     def merge(self,nums,left,mid,right):
 3         helper=[]
 4         i=left
 5         j=mid+1
 6         while i<=mid and j<=right:
 7             if(nums[i]<nums[j]):
 8                 helper.append(nums[i])
 9                 i+=1
10             else:
11                 helper.append(nums[j])
12                 j+=1
13         
14         while i<=mid:
15             helper.append(nums[i])
16             i+=1
17         
18         while j<=right:
19             helper.append(nums[j])
20             j+=1
21         
22         for k in range(len(helper)):
23             nums[k+left]=helper[k]
24 
25 
26     def mergeSort(self,nums):
27         left,right=0,len(nums)-1
28         return self.mergeSort_helper(nums,left,right)
29     
30     def mergeSort_helper(self,nums,left,right):
31         if(left<right):
32             mid=left+((right-left)>>1)
33             self.mergeSort_helper(nums,left,mid)
34             self.mergeSort_helper(nums,mid+1,right)
35             self.merge(nums,left,mid,right)
36 
37         return nums

 

posted @ 2020-03-22 21:12  7aughing  阅读(130)  评论(0编辑  收藏  举报