Sorting algorithms are used to put items of data in order. They can sort values into ascending or descending order and can be used to order both numeric data and text (strings). Common sorting algorithms include the Bubble Sort, Insertion Sort, Merge Sort and Quick Sort
Bubble Sort Algorithm
swapMade=Truewhile swapMade==TrueswapMade=Falsefor i = 0 to len(arr) - 2if arr[i] > arr[i+1]temp=arr[i]arr[i]=arr[i+1]arr[i+1]=tempswapMade=True
Compare each pair of adjacent elements
If they are not in the correct order then swap the elements
If they are in the correct order then do no swap elements
When you reach the end of the array return to the start
Repeat n elements time
Set a flag whenever a swap is made
If by the time the pass is finished, the flag is True...it restarts from the beginning
If the flag it false at the end of a pass, the list is sorted
Insertion Sort Algorithm
for i = 1 to len(arr) - 1j = iwhile j > 0 and arr[j] < arr[j-1]temp = arr[j-1]arr[j-1] = arr[j]arr[j] = tempj = j-1
Split the list into two: a sorted list and an unsorted list
Start with the second item in the list.
Compare with the item before it
Swap the number backwards until it is in the correct position.
Move on to the next item in the unsorted list
split each list in half repeat
until each element is in its own independent array.
Compare the first item with the second item and add together in a new array in the correct order.
Repeat with each subsequent pair
Compare the first item in each pair add the smallest to a new array
Repeat this with each item in the pair until all items added to new array
Combine the two remaining list into one until you have a single array
Quick Sort Algorithm
An example of a recursive quick sort algorithm can be found below
quicksort(arr, low, high)if low < highpivotIndex = partition(arr, low, high)quicksort(arr, low, pivotIndex - 1)quicksort(arr, low, pivotIndex - 1) partition(arr, low, high)pivot = arr[high]i = low - 1for j from low to high - 1if arr[j] <= pivoti = i + 1swap arr[i] and arr[j] swap arr[i + 1] and arr[high]return i + 1
Make the first number a pivot
Put all the numbers > in a sub list in the left of the pivot
Put all the numbers < in a sub list to the right of a pivot
The first number in each sub list becomes a new pivot
Repeat the process until each number becomes a pivot.