Skip to content

Commit 73d51a7

Browse files
committed
adding shell sort
1 parent d65eeb5 commit 73d51a7

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ This is my study repository.
1616
* bubble sort.
1717
* selection sort.
1818
* insertion sort.
19+
* shell sort.
1920

2021
## Link
2122

src/shell_sort.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/env python3
2+
3+
##
4+
# Shell Sort
5+
##
6+
7+
import numpy as np
8+
9+
def shell_sort(array):
10+
"""
11+
Sorts an array using the Shell Sort algorithm.
12+
13+
Shell Sort is an in-place comparison-based sorting algorithm
14+
that generalizes insertion sort to allow the exchange of items
15+
that are far apart. The idea is to arrange the list of elements
16+
so that, starting anywhere, taking every `gap`-th element produces
17+
a sorted list. The algorithm gradually reduces the gap between
18+
elements to be compared.
19+
20+
Parameters:
21+
array (numpy.ndarray): The array to be sorted.
22+
23+
Returns:
24+
numpy.ndarray: The sorted array.
25+
"""
26+
27+
# Start with a gap size of half the length of the array
28+
gap = len(array) // 2
29+
30+
# Continue reducing the gap until it becomes zero
31+
while gap > 0:
32+
# Perform a modified insertion sort for each gap
33+
for i in range(gap, len(array)):
34+
temp = array[i] # Store the current element
35+
j = i # Initialize index j to the current index i
36+
37+
# Shift elements that are greater than temp to the right
38+
while j >= gap and array[j - gap] > temp:
39+
array[j] = array[j - gap]
40+
j -= gap
41+
42+
# Place the temp element in the correct position
43+
array[j] = temp
44+
45+
# Reduce the gap for the next iteration
46+
gap //= 2
47+
48+
return array
49+
50+
# Example usage
51+
sorted_array = shell_sort(np.array([8, 5, 1, 4, 2, 3]))
52+
print(sorted_array)

0 commit comments

Comments
 (0)