Insertion-Sort 9
Insertion-Sort 9
Topperworld.in
Insertion Sort
Insertion Sort: Insertion Sort is a simple sorting algorithm that builds the
final sorted array one item at a time. It is similar to the way you might sort
a hand of playing cards. The algorithm works by taking an element from
the unsorted part of the array and inserting it into its correct position within
the sorted part of the array.
Algorithm:
2. Compare the current element with the elements in the sorted portion
of the array, moving from right to left.
©Topperworld
Data Structure and Algorithm
4. Repeat step 3 until you find the correct position for the current
element.
5. Insert the current element into the correct position in the sorted
portion of the array.
Example:-
9 6 5 0 8 2 7 1 3 4
©Topperworld
Data Structure and Algorithm
©Topperworld
Data Structure and Algorithm
Java Implementation:
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
OUTPUT
Sorted Array:
0 1 2 3 4 5 6 7 8 9
©Topperworld
Data Structure and Algorithm
➔Complexity Analysis:
Insertion Sort is efficient for small datasets and is also used as part of more
advanced sorting algorithms, such as Timsort (used in Python's built-in
sorted function). However, for larger arrays, other sorting algorithms like
Merge Sort or Quick Sort are generally more efficient.
©Topperworld