In this source code example, we will write a code to implement the Insertion Sort algorithm in Python.
The shell sort algorithm sorts a pair of elements that are not in sequence in a collection. The distance between the elements to be compared is decreased sequentially. This algorithm performs more operations and has a greater cache miss ratio than the quick sort algorithm.Shell Sort Algorithm in Python
In this Python program, we will take input from the User or console and print the result to the output:
def shell_sort(collection):
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(collection)):
insert_value = collection[i]
j = i
while j >= gap and collection[j - gap] > insert_value:
collection[j] = collection[j - gap]
j -= gap
if j != i:
collection[j] = insert_value
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(shell_sort(unsorted))
Output:
Enter numbers separated by a comma:
20,15,10,5,3,1,2
[1, 2, 3, 5, 10, 15, 20]
Related Algorithms in Python
- Write a Python program for Linear Search and Binary Search
- Selection Sort Algorithm in Python
- Bubble Sort Algorithm in Python
- Bogo Sort Algorithm in Python
- Bucket Sort Algorithm in Python
- Comb Sort Algorithm in Python
- Counting Sort Algorithm in Python
- Heap Sort Algorithm in Python
- Insertion Sort Algorithm in Python
- Merge Sort Algorithm in Python
- Quick Sort Algorithm in Python
- Shell Sort Algorithm in Python
- Interpolation Search Algorithm in Python