1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
# O(n^2), stable
def bubble_sort(nums):
for i in range(0, len(nums)):
# return early
sorted_flag = False
for j in range(i+1, len(nums)):
if nums[i] > nums[j]:
nums[i],nums[j] = nums[j],nums[i]
# data exchange occurred
sorted_flag = True
if not sorted_flag:
break
# O(n^2), stable
def insertion_sort(nums):
for i in range(1, len(nums)):
val = nums[i]
# comparison with prev one
j = i - 1
# move greater ones backwards
while j >= 0 and nums[j] > val:
nums[j+1] = nums[j]
j -= 1
# reside the small one
nums[j+1] = val
# O(n^2), unstable
def selection_sort(nums):
for i in range(0, len(nums) - 1):
mini = i
for j in range(i+1, len(nums)):
if nums[mini] > nums[j]:
mini = j
nums[mini], nums[i] = nums[i], nums[mini]
# O(nlogn), stable, extra space O(n)
def merge_sort(nums: List[int]):
def merge(arr1: List[int], arr2: List[int]) -> List[int]:
ret = []
i,j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] > arr2[j]:
ret.append(arr2[j])
j += 1
else:
ret.append(arr1[i])
i += 1
while i < len(arr1):
ret.append(arr1[i])
i += 1
while j < len(arr2):
ret.append(arr2[j])
j += 1
return ret
if len(nums) <= 1:
return nums
m = len(nums) // 2
left = merge_sort(nums[:m])
right = merge_sort(nums[m:])
return merge(left, right)
# quick sort
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# in-place version
def quicksort(arr, low, high):
if low < high:
# Partition the array and get the pivot index
pivot_index = partition(arr, low, high)
# Recursively sort the elements before and after partition
quicksort(arr, low, pivot_index - 1)
quicksort(arr, pivot_index + 1, high)
def partition(arr, low, high):
# Select the pivot (here we choose the last element as the pivot)
pivot = arr[high]
# Initialize the index of the smaller element
i = low - 1
# Rearrange the elements in relation to the pivot
for j in range(low, high):
if arr[j] <= pivot:
i += 1
# Swap elements if the current element is smaller than or equal to the pivot
arr[i], arr[j] = arr[j], arr[i]
# Swap the pivot element with the element at i+1 position
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
|