When it is required to implement shell sort, a function is defined, and this takes a list and the length of the list as arguments. This list is sorted up to a specific number of elements, wherein the number of elements is the largest value. This is done until the number of elements has the smallest value.
This is done for all sub-lists in the list, and all these sub-lists are sorted.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
Below is a demonstration of the same −
def shell_sort(my_list, list_len): interval = list_len // 2 while interval > 0: for i in range(interval, list_len): temp = my_list[i] j = i while j >= interval and my_list[j - interval] > temp: my_list[j] = my_list[j - interval] j -= interval my_list[j] = temp interval //= 2 my_list = [ 45, 31, 62, 12, 89, 5, 9, 8] list_len = len(my_list) print ("The list before sorting is :") print(my_list) shell_sort(my_list, list_len) print ("\nThe list after performing shell sorting is :") print(my_list)
The list before sorting is : [45, 31, 62, 12, 89, 5, 9, 8] The list after performing shell sorting is : [5, 8, 9, 12, 31, 45, 62, 89]