Class DirectInsertion
java.lang.Object
topics.sorting.insertion.DirectInsertion
- All Implemented Interfaces:
SortingAlgorithm
Direct Insertion Sort
An educational sorting implementation that builds the final sorted array one item at a time. It operates similarly to how one might sort a hand of playing cards: picking an element and inserting it into its mathematically correct position among the already sorted elements to its left.
Algorithm Steps
- Assume the first element (index 0) is already sorted.
- Pick the next element, referred to as the
key. - Compare the key with elements in the sorted sub-array to its left.
- Shift all elements strictly greater than the key one position to the right.
- Insert the key into the newly vacated correct position.
- Repeat until the boundary reaches the end of the array.
Complexity Analysis
- Time Complexity (Worst/Average):
O(N²)- Occurs when the array is in reverse order. - Time Complexity (Best):
O(N)- Occurs when the array is already sorted (the innerwhileloop never executes). - Space Complexity:
O(1)- Sorts entirely in-place without recursion overhead. - Stability: Yes - Maintains the relative order of equal elements because it only shifts strictly greater elements.
- Author:
- vicegd
- See Also:
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
DirectInsertion
public DirectInsertion()
-
-
Method Details
-
sort
public void sort(int[] elements) Description copied from interface:SortingAlgorithmSorts the elements in-place silently.- Specified by:
sortin interfaceSortingAlgorithm- Parameters:
elements- The array of integers to be sorted.
-
sort
public void sort(int[] elements, boolean trace) Description copied from interface:SortingAlgorithmSorts the elements in-place, optionally emitting step-by-step traces to visualize the algorithmic progression.- Specified by:
sortin interfaceSortingAlgorithm- Parameters:
elements- The array of integers to be sorted.trace- Iftrue, logs the internal state during execution.
-