The document discusses insertion sort, a simple sorting algorithm that builds a sorted array by comparing and inserting elements into their proper position in each iteration. It provides examples of sorting contact lists or shopping items by price. The steps of insertion sort are outlined, including picking the next element, shifting greater elements over, and inserting the value. Pseudocode of the algorithm is given. Real-life examples of sorting coats by size using insertion sort are then described step-by-step.
2. what is sorting in data structure
Sorting is the process of arranging the
data in ascending and descending order.
3. Some real life examples
The contact list in your phone is sorted.
While shopping on flip kart or amazon, you sort
items based on your choice, that is, price low to
high or high to low
4. What is Insertion Sort
Insertion sort is a simple sorting algorithm that
builds the final sorted array (or list) one item at a
time by comparisons.
5. Insertion Algorithms: Steps on how it works:
1) If it is the first element, it is
already sorted.
2) Pick the next element.
3) Compare with all the elements in
sorted sub-list.
4) Shift all the elements in sorted
sub-list that is greater than the
value to be sorted.
5) Insert the value.
6) Repeat until list is sorted.
6. Insertion Sort Algorithm
Algorithm: Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i = j – 1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
8. Insertion Sort Algorithm
Algorithm: Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i = j – 1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key
n times
n-1 times
n-1 times
n-1,
𝑛∗(𝑛−1)
2
times
n-1 times
Times
Cost
C1
C2
C3
C4
C5
C6
C7
n-1,
𝑛∗(𝑛−1)
2
times
n-1,
𝑛∗(𝑛−1)
2
times
9. Real life example
1. We have set of Coats, which have different sizes.
2. Coats are kept unsorted.
3. Now we will sort them in ascending order using
Insertion Sort technique.
10 7 9
11 15 4
10. 4. According to insertion sort algorithm we will consider first
number(coat size) as a sorted list and now we will see next
size of coat is less then or greater then sorted list of coat.
10 7 9
11 15 4
We considered coat size 10 as a
sorted list.
11. 5. We will keep next size of coat in a separate place and see If next size of
coat is less then sorted list of coat we will swap both coats otherwise not.
10 9
11 15 4
7
Sorted List
Next size
12. 6. As we can see that next size of coat is less then sorted list of coat so we
will swap both coats and we will consider both coats as a member od
sorted list.
7. Now we will start to compare every next size of coat with sorted list and
swap them if required
10 9
11 15 4
7
Sorted List
7<10
swap
13. 8. Now we can see we have two coats of different sizes in sorted order in
sorted list, we will repeat step 5,6,7 until unless we keep all coats in sorted
order.
7
9
11 15 4
10
Sorted List