Skip to content

Instantly share code, notes, and snippets.

@Jackliu91
Created January 24, 2019 03:39
Show Gist options
  • Save Jackliu91/7ae1ca2018b400746f6df717098981c1 to your computer and use it in GitHub Desktop.
Save Jackliu91/7ae1ca2018b400746f6df717098981c1 to your computer and use it in GitHub Desktop.
[sort algrithm] #python
def selection_sort(arr):
for i in range(len(arr)):
index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[index]:
index = j
arr[i], arr[index] = arr[index], arr[i]
return arr
def insertion_sort(arr):
for i in range(1, len(arr)):
temp = arr[i]
j = i - 1
while j >= 0 and arr[j] > temp:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = temp
return arr
def merge(left, right):
result = []
while left and right:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
if left:
result += left
if right:
result += right
return result
def merge_sort_recursive(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment