Sorting Algorithms
Sorting Algorithms
1. Find the middle point to divide the array into two halves:
2. middle m = l + (r – l)/2
3. Call the function recursively:
4. Call mergeSort function for first half:
5. Call mergeSort(arr, l, m)
6. Call mergeSort function for second half:
7. Call mergeSort(arr, m + 1, r)
8. Merge the two halves sorted in steps 2 and 3:
9. Call merge(arr, l, m, r)
Merge ( arr[] , l , m , r )
1. Set value of I and j to 0, k to l
2. Set value of n1 to ( m – l + 1 ) and n2 to ( r – m )
3. Create array L with n1 elements and array R with n2 element
4. Copy the first half to array L
5. Copy the second half to array R
6. While i is smaller than n1 and j is smaller than n2 do steps 7 through 13
7. If element at location i of array L is smaller than element at location j of array R do steps 8 through 12
8. Copy it to position k of the input array
9. Increase i by 1
10. Else ( If element at location i of array L is greater than element at location j of array R )
11. Copy it to position k of the input array
12. Increase j by 1
13. Increase k by 1
14. Stop
Time efficiency
Merge sort • Total step log( n + 1 ).
efficiency • Running time O(n).
Time complexity of O(n*log n).
Quick sort
Partioning the array to be sorted and
each partition in turn sorted
recursively.
main function
Time complexity
• Best case: O(n*logn).
• Average case: O(n*logn).
• Worse case: O(n2).
• Worst case in quick sort rarely occurs because by changing the choice
of pivot, it can be implemented in different ways.
Worst case in quicksort can be avoided by choosing the right pivot
element.
• The bubble sort is an easy way to
arrange data in ascending or
descending order.
• Operating principle:
Bubble sort Compare 2 elements that are side by
side and swap if necessary
Repeat that step to the end of the list
Go through the list again and again
until there is no swap to do left
Bubble sort pseudo code
Do
Set swap flag to false.
For count is set to each subscript in array from 0
through the next-to-last subscript
If array[count] is greater than array[count + 1]
Swap the contents of array[count] and
array[count + 1].
Set swap flag to true.
End If.
End For.
While any elements have been swapped
Bubble sort efficiency
Time complexity
• Best case: O(n)
• If the array is all but sorted
• Inner Loop won’t execute so only some constant time the statement will run
• Worse case: O(n2)
• Array element in reverse sorted order
Space Complexity
• Since no extra space beside n variables is needed for sorting so
Space Complexity = O(n)