Table of Contents

Sort Algorithms
Time Complexity Space
Algorithm Best Avegage Worst Worst
Bubble Sort Ω(n) Θ(n2) O(n2) O(1)
Insertion Sort Ω(n) Θ(n2) O(n2) O(1)
Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n)
Quicksort (quick pivot) Ω(n log(n)) Θ(n log(n)) O(n2) O(1)


Bubble Sort

public void bubbleSort(int[] numbers) {

	boolean numbersSwitched;
	do {

		numbersSwitched = false;
		for(int i = 0; i < numbers.length - 1; i++) {
			if(numbers[i + 1] < numbers[i]) {
				int tmp = numbers[i + 1];
				numbers[i + 1] = numbers[i];
				numbers[i] = tmp;
				numbersSwitched = true;
			}
		}

	} while(numbersSwitched);
}
	
Insertion Sort

public static List binaryInsertSort(final List<Integer> list) {
		
	if(list == null || list.size() < 2)		return list;

	final List<Integer> sortedList = new ArrayList<>(list.size());

	tag: for(Integer num: list) {

		int start = 0;
		int section = sortedList.size() / 2;	// list section
		while(section > 5) {

			if(sortedList.get(start + section) < num)	start += section;
			section /= 2;
		}

		for(; start < sortedList.size(); start++) {
			if(num < sortedList.get(start)) {
				sortedList.add(start, num);
				continue tag;
			}
		}

		sortedList.add(num);
	}

	return sortedList;
}
	
Merge Sort

public static List<Integer> mergesort(final List<Integer> values) {

	if(values.size() < 2) {	return values;		}

	final List<Integer> leftHalf = values.subList(0, values.size() / 2);
	final List<Integer> rightHalf = values.subList(values.size() / 2, values.size());

	return merge(mergesort(leftHalf), mergesort(rightHalf));
}

private static List<Integer> merge(final List<Integer> left, final List<Integer> right) {

	int leftPtr = 0;
	int rightPtr = 0;

	final List<Integer> merged = new ArrayList<>(left.size() + right.size());
	while(leftPtr < left.size() && rightPtr < right.size()) {
		if(left.get(leftPtr) < right.get(rightPtr)) {
			merged.add(left.get(leftPtr));
			leftPtr++;
		}
		else {
			merged.add(right.get(rightPtr));
			rightPtr++;
		}
	}

	while(leftPtr < left.size()) {
		merged.add(left.get(leftPtr));
		leftPtr++;
	}

	while(rightPtr < right.size()) {
		merged.add(right.get(rightPtr));
		rightPtr++;
	}

	return merged;
}
	
Quicksort (quick pivot)

public static List<Integer> quicksort(List<Integer> numbers) {

	if(numbers.size() < 2) {	return numbers;		}

	final Integer pivot = numbers.get(0);
	final List<Integer> lower = new ArrayList<>();
	final List<Integer> higher = new ArrayList<>();

	for(int i = 1; i < numbers.size(); i++) {

		if(numbers.get(i) < pivot) {
			lower.add(numbers.get(i));
		}
		else {
			higher.add(numbers.get(i));
		}
	}

	final List<Integer> sorted = quicksort(lower);
		sorted.add(pivot);
		sorted.addAll(quicksort(higher));

	return sorted;
}