# Sorting Algorithms

### Time complexity of sorting algorithms

• From the beginning of an array, it finds minimum element in unsorted subarray (right side) and puts the element at the end of sorted subarray (left side) until it gets to the end.

e.g. Given unsorted array: 64  25  12  22  11. Red colored number is minimum in unsorted subarray, and underline represents a sorted subarray.

64  25  12  22  11

11  25  12  22  64

11  12  25  22  64

11  12  22  25  64

11  12  22  25  64   (Completed)

• It repeatedly swapping the adjacent elements if they are in wrong order.

e.g. Given unsorted array: 5  1  4  2  8. Two red colored numbers get compared and swapped.

[ 1st Pass ]

5  1  4  2  8

1  5  4  2  8

1  4  5  2  8

1  4  2  5  8

[ 2nd Pass ]

1  4  2  5  8

1  4  2  5  8

1  2  4  5  8

1  2  4  5  8

Now the array is sorted, but it goes one more step checking whether whole pass doesn’t have any swap.

[ 3rd Pass ]

1  2  4  5  8

1  2  4  5  8

1  2  4  5  8

1  2  4  5  8

• It works the way we sort playing cards in our hands.
• From the beginning of an array, next element gets compares with numbers from the end of sorted subarray and gets placed in right position.

• It builds a max heap (a parent node is larger than all children nodes) from the input data.
• It is similar to selection sort, but it finds max instead of minimum. However by using max heap, sorting time is faster than selection sort.

• It is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot.
3. Pick a random element as pivot.
4. Pick median as pivot.

The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.