Skip to content

Instantly share code, notes, and snippets.

@rer145
Last active November 11, 2017 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rer145/2ae526a89db1f9ef8b1b07c62e593aa1 to your computer and use it in GitHub Desktop.
Save rer145/2ae526a89db1f9ef8b1b07c62e593aa1 to your computer and use it in GitHub Desktop.
Different sorting methods in python
def bubble_sort(L):
for i in range(len(L)-1, 0, -1):
for j in range(i):
if L[j] > L[j+1]:
temp = L[j]
L[j] = L[j+1]
L[j+1] = temp
def selection_sort(L):
for i in range(len(L)-1, 0, -1):
max_pos = 0
for j in range(1, i+1):
if L[j] > L[max_pos]:
max_pos = j
temp = L[i]
L[i] = L[max_pos]
L[max_pos] = temp
def insertion_sort(L):
for i in range(1, len(L)):
current = L[i]
pos = i
while pos > 0 and L[pos-1] > current:
L[pos] = L[pos-1]
pos -= 1
L[pos] = current
def merge_sort(L):
if len(L) > 1:
mid = len(L)//2
left = L[:mid]
right = L[mid:]
merge_sort(left)
merge_sort(right)
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
L[k] = left[i]
i += 1
else:
L[k] = right[j]
j += 1
k += 1
while i < len(left):
L[k] = left[i]
i += 1
k += 1
while j < len(right):
L[k] = right[j]
j += 1
k += 1
def quick_sort(L):
quick_sort_helper(L, 0, len(L)-1)
def quick_sort_helper(L, first, last):
if first < last:
split = quick_sort_partition(L, first, last)
quick_sort_helper(L, first, split-1)
quick_sort_helper(L, split+1, last)
def quick_sort_partition(L, first, last):
pivot = L[first]
left = first+1
right = last
done = False
while not done:
while left <= right and L[left] <= pivot:
left += 1
while L[right] >= pivot and right >= left:
right -= 1
if right < left:
done = True
else:
temp = L[left]
L[left] = L[right]
L[right] = temp
temp = L[first]
L[first] = L[right]
L[right] = temp
return right
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment