5. • Insertion sort is a simple sorting algorithm that builds the
final sorted array one item at a time.
• Insertion sort keeps a prefix of the array sorted.
• At each step, this prefix is grown by inserting the next
value into it at the correct place.
• Eventually, the prefix is the entire array, which is therefore
sorted.
6. Algorithm:
1. If it is the first element, it is already sorted. return 1.
2. Pick next element.
3. Compare with all elements in the sorted sub-list.
4. Shift all the elements in the sorted sub-list that is
greater than the
value to be sorted.
5. Insert the value.
6. Repeat until list is sorted.
7. Advantages:
• The main advantage of the insertion sort is its
simplicity.
• It also exhibits a good performance when dealing with
a small list.
Disadvantages:
• The disadvantage of the insertion sort is that it does
not perform as well as other, better sorting algorithms.
• The insertion sort is particularly useful only when
sorting a list of few items.
8.
9. • The quick sort works on the divide-and-conquer principle.
• Based on partitioning of array of data into smaller arrays.
• First, it partitions the list of items into two sublists based
on a pivot element.
• All elements in the first sublist are arranged to be smaller
than the pivot, while all elements in the second sublist are
arranged to be larger than the pivot.
• The same partitioning and arranging process is performed
repeatedly on the resulting sublists until the whole list of
items are sorted.
10. Given a pivot, partition the elements of the array such that
the resulting array consists of:
1. One sub-array that contains elements >= pivot
2. Another sub-array that contains elements < pivot
The sub-arrays are stored in the original data array.
Partitioning loops through, swapping elements below/above
pivot.
11.
12. Algorithm:
Given an array of n elements (e.g., integers):
If array only contains one element, return
Else
– pick one element to use as pivot.
– Partition elements into two sub-arrays:
• Elements less than or equal to pivot
• Elements greater than pivot
– Quicksort two sub-arrays
– Return results
14. Advantage:
• The quick sort is regarded as the best sorting algorithm.
• This is because of its significant advantage in terms of
efficiency because it is able to deal well with a huge list of
items.
Disadvantage:
• Implementation of the algorithm may result in stack
overflow error, since it may require O(n) embedded
recursive calls.