
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Shell Sort in Python
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 −
Example
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)
Output
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]
Explanation
- A method named 'shell_sort' is defined, that takes the list, and the length of the list as arguments.
- The 'interval' variable is defined by using the '//' bitwise operator.
- It performs floor division.
- It rounds down the value to the nearest whole number.
- The list is iterated over, and a temporary variable is created.
- The 'interval' variable is compared with every index of the list, and every element in the list is compared to the temporary variable.
- The 'interval' variable is again used to perform floor division.
- The list is defined, and is displayed on the console.
- The method is called by passing this list, and its length.
- The output is displayed on the console.
Advertisements