Implemented Shell Sort Algorithm in Java #326
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Shell Sort is an in-place comparison-based sorting algorithm. It is a generalization of insertion sort, allowing the exchange of items that are far apart. The method starts by sorting elements that are far apart, reducing the gap between elements as it progresses, and eventually performs a final insertion sort.
The gap sequence typically starts with half the size of the array and is repeatedly halved until it becomes 1. This technique helps reduce the time complexity compared to the standard insertion sort, especially for medium-sized arrays.
Working of Shell Sort Algorithm
1. Initial Gap Selection:
The algorithm starts with an initial gap, typically half the length of the array (n/2).
2. Gapped Insertion Sort:
For each gap, the algorithm performs a modified insertion sort where elements that are far apart (determined by the gap) are compared and swapped if necessary.
For instance, with a gap of 5, the element at position 0 is compared to the element at position 5, the element at position 1 is compared to the element at position 6, and so on.
3. Gap Reduction:
The gap is then reduced by half in each iteration until the gap becomes 1, which is equivalent to a regular insertion sort.
4. Final Pass:
Once the gap is 1, the algorithm performs the final pass similar to insertion sort, which ensures that the array is fully sorted.
5. Termination:
The process stops when the gap is reduced to 0, meaning the entire array has been sorted.
Key Steps of the Algorithm
1. For each gap from n/2 to 1:
2. Continue until the entire array is sorted.
Test Cases
Test Case 1: Basic test case with random elements
Input:
Expected Output:
Test Case 2: Already sorted array
Input:
Expected Output:
Test Case 3: Reverse sorted array
Input:
Expected Output:
Test Case 4: Array with duplicate elements
Input:
Expected Output:
Fixes #293