Basic Sorting Algorithms

Bubble Sort

A sorting algorithm that is based upon comparing pairs of values and swapping their places if necessary.

Overall Idea:

- (L→ List, i→ index, i starts at 1)    
- Look at L[i] and L[i-1] if they are not sorted, swap locations
- Repeat as you increase i and until no swap occurs

Bubble Sort Demonstration:

repeat until swapped is false
	swapped = false
	for i = 1 to N-1 (inclusively)
		if A[i-1] > A[i] then
			swap(A[i-1],A[i])
			swapped = true

Insertion Sort

A sorting algorithm that iterates sorts from the bottom one element at a time.

Overall Idea:

  • Since a singleton list is already sorted, it will grow its “sorted” list with the next value from the list

  • It grabs the next value, removes it, and places in the correct location

  • It does this until the list is fully sorted

Insertion Sort Demonstration:

-- Let A be a List, i and j both be indexes

i = 1
while i < length(A)
	j = i
	while j > 0 and A[j-1] > A[j]
		swap A[j] and A[j-1]
		j = j - 1
	i = i + 1

Selection Sort

A sorting algorithm that uses two lists: sorted list and unsorted list.

It brings the smallest values to the sorted list then removed the smallest value in the unsorted list .

Overall Idea:

  • At beginning, sorted list is empty and unsorted list is full

  • Choose the smaller(or largest) value from the unsorted list, and append it to the sorted list

  • Repeat until unsorted list is empty

Selection Sort Demonstration:

-- Let A be the unsorted list, and let B be the sorted list; B starts empty

repeat until A is empty
    Target = the smallest value from A
    Append Target to B
    Remove target from A

Complexity of Bubble, Insertion, and Selection Sort.

The 3 sorting algorithms are learned together due to their Big-O Notation.

All 3 algorithms are classified as O(n2)O(n^2).

Last updated