Skip to content

Commit c99077c

Browse files
Merge pull request #6 from Sphesihlebjamile/sort/insertion-sort
Insertion Sort Algorithm
2 parents 58fae44 + 12fd2f1 commit c99077c

5 files changed

Lines changed: 88 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This repository is one where we document the implementations and usage of differ
88
- [Sort Algorithms](./src/com/sketch/sort/)
99
- [Quick Sort](./src/com/sketch/sort/quicksort/QuickSort.md)
1010
- [Selection Sort](./src/com/sketch/sort/selectionsort/SelectionSort.md)
11+
- [Insertion Sort](./src/com/sketch/sort/insertionsort/InsertionSort.md)
1112

1213
## Contributions
1314
This repository is open-source and available to everyone to wants to learn DSA or wants to contibute to documenting other algorithms.

‎src/com/sketch/Main.java‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
package com.sketch;
22

3-
import com.sketch.sort.quicksort.QuickSort;
3+
import com.sketch.sort.insertionsort.InsertionSort;
44

55
import java.util.Arrays;
66
import java.util.Random;
77

88
public class Main {
99
public static void main(String[] args){
10-
int[] unsortedArray = new int[100];
10+
int[] unsortedArray = new int[10000];
1111
Random random = new Random();
1212
for(int i = 0; i < unsortedArray.length; i++){
13-
unsortedArray[i] = random.nextInt(20);
13+
unsortedArray[i] = random.nextInt(50);
1414
}
1515

1616
int[] unsortedArrayResult = new int[unsortedArray.length];
1717
System.arraycopy(unsortedArray, 0, unsortedArrayResult, 0, unsortedArray.length);
1818

19-
QuickSort.sort(unsortedArrayResult, 0, unsortedArrayResult.length - 1);
19+
long startTime = System.nanoTime();
2020

21-
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArray));
22-
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArrayResult));
21+
InsertionSort.sort(unsortedArrayResult);
22+
23+
long endTime = System.nanoTime();
24+
double duration = (endTime - startTime) / 1_000_000.0;
25+
26+
System.out.println("Default Array: " + Arrays.toString(unsortedArray));
27+
System.out.println("Sorted Array: " + Arrays.toString(unsortedArrayResult));
28+
System.out.println("Execution Time: " + duration + "ms");
2329
}
2430
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.sketch.sort.insertionsort;
2+
3+
public class InsertionSort {
4+
public static void sort(int[] array){
5+
for(int i = 1; i < array.length; i++){
6+
int currentValue = array[i];
7+
int j = i - 1;
8+
while (j >= 0 && array[j] > currentValue){
9+
array[j + 1] = array[j];
10+
j--;
11+
}
12+
array[j + 1] = currentValue;
13+
}
14+
}
15+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Insertion Sort
2+
3+
Insertion Sort is a simple, comparison-based algorithm that builds a sorted list one element at a time.
4+
It works similarly to the way most people instinctively sort a hand of playing cards - by picking up one card at a time and inserting it into its correct position relative to the cards already held.
5+
6+
The algorithm is classified as an in-place and stable sorting algorithm =, meaning it requires no additional memory proportional to the input size,
7+
and it preserves the relative order of elements with equal keys.
8+
9+
![img.png](img.png)
10+
11+
Insertion Sort divides the input list into two conceptual parts:
12+
- A sorted portion on the left, and
13+
- An unsorted portion on the right.
14+
15+
At the start, the sorted portion contains only the first element, since a single element is trivially sorted.
16+
The algorithm then proceeds through the following steps for each remaining element:
17+
- The current element is picked from the unsorted portion - *this is called the key*.
18+
- The key is compared against the elements in the sorted portion, moving from right to left.
19+
- Any sorted element that is greater than the key is shifted one position to the right to make room.
20+
- Once the correct position is found, the key is inserted there.
21+
- This process repeats until all elements have been moved from the unsorted portion into the sorted portion.
22+
23+
By the time the algorithm reaches the last element, the entire list i guaranteed to be sorted.
24+
25+
## Interesting facts
26+
- Insertion Sort is one of the few sorting algorithms that can sort a list as it receives it - it is an online algorithm, meaning it does not need all elements to be present before it begins sorting.
27+
- Unlike Bubble Sort and [Selection Sort](../selectionsort/SelectionSort.md), Insertion Sort performs very well on nearly sorted data, achieving close to linear time (O(n)) is such cases.
28+
- The algorithm is naturally adaptive - its performance improves the more sorted the input already is.
29+
- Insertion Sort is stable, meaning two elements with equal values will retain their original relative order after sorting.
30+
- It is widely used in education settings as an introduction to sorting due to its intuitive, step-by-step nature.
31+
32+
## Complexity Analysis
33+
- Time Complexity
34+
- Best Case: O(n)
35+
- Average Case: O(n^2)
36+
- Worst Case: O(n^2)
37+
- Auxiliary Space:
38+
- Best Case: O(1)
39+
- Average Case: O(1)
40+
- Worst Case: O(1)
41+
42+
## Advantages
43+
- Simple to understand and implement, making it ideal for learning and teaching sorting concepts.
44+
- Very efficient on small datasets, often outperforming more complex algorithms like [Quick Sort](../quicksort/QuickSort.md) or Merge Sort at small sizes.
45+
- Performs exceptionally well o nearly sorter or partially sorted data due to its adaptive nature.
46+
- In-place sorting requires no extra memory allocation, making it memory efficient.
47+
- Stable sort preserves the original order of equal elements, which is important in certain use cases such as sorting records with multiple fields.
48+
- Online algorithm - can sort data as it arrives without needing the full dataset upfront.
49+
50+
## Disadvantages
51+
- Inefficient on large datasets due to its O(n^2) average and worst-case time complexity.
52+
- Performance degrades significantly when the data is in reverse order, as every element must shift past all previously sorted elements.
53+
- Not suitable as a general-purpose sorting algorithm for large-scale applications where performance is critical.
54+
- Compared to divide-and-conquer algorithms like Merge Sort or [Quick Sort](../quicksort/QuickSort.md), ir does not scale well as input size grows.
55+
56+
## Applications
57+
- Used as a subroutine in Bucket Sort
58+
- Can be useful when array is already almost sorted
59+
- Since Insertion sort is suitable for small sized arrays, it is used in Hybrid Sorting algorithms along with other efficient algorithms like [Quick Sort](../quicksort/QuickSort.md) and Merge Sort. When the subarray size becomes small, we switch to insertion sort in these recursive algorithms.
60+
- Embedded Systems: In low-memory environments such as micro-controllers, Insertion Sort's in-place O(1) space requirement makes it a practical choice.
86 KB
Loading

0 commit comments

Comments
 (0)