class Solution():
def mergeSort(self, nums):
def mergeSortR(nums):
if len(nums) <= 1:
return nums
mid = len(nums)//2
leftList = nums[:mid]
rightList = nums[mid:]
leftList = mergeSortR(leftList)
rightList = mergeSortR(rightList)
i, j = 0, 0
newList = []
while i < len(leftList) and j < len(rightList):
if leftList[i] <= rightList[j]:
newList.append(leftList[i])
i += 1
else:
newList.append(rightList[j])
j += 1
if i == len(leftList):
newList = newList + rightList[j:]
else:
newList = newList + leftList[i:]
return newList
return mergeSortR(nums)
if __name__ == '__main__':
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(Solution().mergeSort(nums))
#################################################################################
class Solution():
def __init__(self, nums):
self.nums = nums
def quickSort(self, start, end):
if start+1 >= end:
return
index = self.partition(start, end)
self.quickSort(start, index - 1)
self.quickSort(index + 1, end)
return self.nums
def partition(self, start, end):
## how to write the pivot function!!
pivot = self.nums[end]
small_ind = start-1
for i in range(start, end):
if self.nums[i] < pivot:
small_ind += 1
if small_ind != i:
self.nums[i], self.nums[small_ind] = self.nums[small_ind], self.nums[i]
small_ind += 1
self.nums[end], self.nums[small_ind] = self.nums[small_ind], self.nums[end]
return small_ind
if __name__ == '__main__':
nums = [4, 3, 45, 2, 2, 35, 4]
print(Solution(nums).quickSort(0, len(nums)-1))
###############################################################################################
class Solution():
def __init__(self, nums, gaps):
self.nums = nums
self.gaps = gaps
def shell_sort(self):
# not the best way!!
for gap in self.gaps:
for g in range(gap):
for i in range(g, len(self.nums), gap):
temp = self.nums[i]
for j in range(i, g-1, -gap):
if temp < self.nums[j-gap]:
self.nums[j] = self.nums[j-gap]
else:
break
self.nums[j] = temp
return self.nums
def shell_sort_official(self):
for gap in self.gaps:
for i in range(gap, len(self.nums)):
temp = self.nums[i]
for j in range(i, gap-1, -gap):
if self.nums[j-gap] > temp:
self.nums[j] = self.nums[j-gap]
else:
break
self.nums[j] = temp
return self.nums
if __name__ == '__main__':
nums = [13,14, 94 ,33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
gaps = [5, 3, 1]
s = Solution(nums, gaps)
print(s.shell_sort_official())