Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Implement Shell Sort
Shell Sort is an efficient sorting algorithm that improves upon insertion sort by comparing elements separated by a gap (interval). It starts with a large gap and gradually reduces it until the gap becomes 1, at which point it performs a final insertion sort on the nearly sorted array.
The algorithm works by sorting sub-arrays of elements that are a certain distance apart, making the overall array more organized with each pass ?
How Shell Sort Works
Shell Sort follows these steps ?
- Start with a gap (interval) equal to half the array length
- Compare and sort elements that are gap positions apart
- Reduce the gap by half and repeat
- Continue until gap becomes 1 (performs final insertion sort)
Implementation
def shell_sort(arr):
n = len(arr)
interval = n // 2
while interval > 0:
for i in range(interval, n):
temp = arr[i]
j = i
# Compare elements separated by interval
while j >= interval and arr[j - interval] > temp:
arr[j] = arr[j - interval]
j -= interval
arr[j] = temp
# Reduce interval by half
interval //= 2
# Test the shell sort algorithm
numbers = [45, 31, 62, 12, 89, 5, 9, 8]
print("Original array:")
print(numbers)
shell_sort(numbers)
print("\nArray after Shell Sort:")
print(numbers)
Original array: [45, 31, 62, 12, 89, 5, 9, 8] Array after Shell Sort: [5, 8, 9, 12, 31, 45, 62, 89]
Step-by-Step Example
Let's trace through the sorting process with a smaller array ?
def shell_sort_verbose(arr):
n = len(arr)
interval = n // 2
print(f"Starting array: {arr}")
pass_num = 1
while interval > 0:
print(f"\nPass {pass_num}: Gap = {interval}")
for i in range(interval, n):
temp = arr[i]
j = i
while j >= interval and arr[j - interval] > temp:
arr[j] = arr[j - interval]
j -= interval
arr[j] = temp
print(f"Array after pass {pass_num}: {arr}")
interval //= 2
pass_num += 1
# Demonstrate with smaller array
data = [64, 34, 25, 12, 22, 11]
shell_sort_verbose(data)
Starting array: [64, 34, 25, 12, 22, 11] Pass 1: Gap = 3 Array after pass 1: [12, 22, 11, 64, 34, 25] Pass 2: Gap = 1 Array after pass 2: [11, 12, 22, 25, 34, 64]
Time Complexity
| Case | Time Complexity |
|---|---|
| Best Case | O(n log n) |
| Average Case | O(n^1.25) |
| Worst Case | O(n²) |
Advantages
- More efficient than simple insertion sort for larger datasets
- In-place sorting algorithm (requires only O(1) extra memory)
- Adaptive - performs better on partially sorted arrays
- Stable sorting algorithm
Conclusion
Shell Sort is an efficient improvement over insertion sort that reduces the number of shifts by comparing elements separated by gaps. It's particularly useful for medium-sized arrays where simple algorithms are too slow and complex algorithms are overkill.
