Skip to content

Instantly share code, notes, and snippets.

@czs0x55aa
Last active October 1, 2017 03:56
Show Gist options
  • Save czs0x55aa/1abb82db88e530cb769e2713b0bb6156 to your computer and use it in GitHub Desktop.
Save czs0x55aa/1abb82db88e530cb769e2713b0bb6156 to your computer and use it in GitHub Desktop.
Sorting Algorithms with Python

QuickSort

def quickSort(arr):
	if len(arr) < 2:
		return arr

	pivot = arr[0]
	i = 0
	for j in range(len(arr)-1):
		if arr[j+1] < pivot:
			arr[j+1], arr[i+1] = arr[i+1], arr[j+1]
			i += 1
	arr[0], arr[i] = arr[i], arr[0]
	return quickSort(arr[:i]) + [arr[i]] + quickSort(arr[i+1:])
import random

# quick sort
def quickSort(arr):
	if len(arr) < 2:
		return arr

	pivot = random.choice(arr)
	less = [x for x in arr if x < pivot]
	more = [x for x in arr if x >= pivot]
	return quickSort(less) + quickSort(more)

MergeSort

def merge(left, right):
	i, j = 0, 0
	res = []
	while i < len(left) and j < len(right):
		if left[i] <= right[j]:
			res.append(left[i])
			i += 1
		else:
			res.append(right[j])
			j += 1
	return res + left[i:] + right[j:]

def mergeSort(arr):
	if len(arr) < 2:
		return arr
	index = len(arr) / 2
	left = mergeSort(arr[:index])
	right = mergeSort(arr[index:])
	return merge(left, right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment