Skip to content

Instantly share code, notes, and snippets.

@rogerwschmidt
Last active August 31, 2017 15:48
Show Gist options
  • Select an option

  • Save rogerwschmidt/0fca9461d7ae8ab0d708948b43c7e7ff to your computer and use it in GitHub Desktop.

Select an option

Save rogerwschmidt/0fca9461d7ae8ab0d708948b43c7e7ff to your computer and use it in GitHub Desktop.

Sorting

Objectives

  • Implement a bubble sort algorithm
  • Implement a selection sort algorithm
  • Implement an insertion sort algorithm

Implement a bubble sort algorithm

  • Largest items bubble to the top.
procedure bubbleSort( A : list of sortable items )
    n = length(A)
    repeat 
        swapped = false
        for i = 1 to n-1 inclusive do
            /* if this pair is out of order */
            if A[i-1] > A[i] then
                /* swap them and remember something changed */
                swap( A[i-1], A[i] )
                swapped = true
            end if
        end for
    until not swapped
end procedure

Implement a selection sort algorithm

  • Select the smallest, move to the front.
/* a[0] to a[n-1] is the array to sort */
int i,j;
int n;

/* advance the position through the entire array */
/*   (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) 
  {
    /* find the min element in the unsorted a[j .. n-1] */

    /* assume the min is the first element */
    int iMin = j;
    /* test against elements after j to find the smallest */
    for (i = j+1; i < n; i++) {
        /* if this element is less, then it is the new minimum */
        if (a[i] < a[iMin]) {
            /* found new minimum; remember its index */
            iMin = i;
        }
    }

    if(iMin != j) 
    {
        swap(a[j], a[iMin]);
    }
}

Implement an insertion sort algorithm

  • For every item, find where it belongs, then instert it there.
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
    end while
    i ← i + 1
end while
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment