Python Example – Write a Python program to sort a list of elements using shell sort algorithm

Hits: 6

(Python Example for Citizen Data Scientist & Business Analyst)

 

Write a Python program to sort a list of elements using shell sort algorithm.

Note : According to Wikipedia “Shell sort or Shell’s method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange.”

 

Sample Solution:

Python Code:


def shellSort(alist):
    sublistcount = len(alist)//2
    while sublistcount > 0:
      for start_position in range(sublistcount):
        gap_InsertionSort(alist, start_position, sublistcount)

      print("After increments of size",sublistcount, "The list is",nlist)

      sublistcount = sublistcount // 2

def gap_InsertionSort(nlist,start,gap):
    for i in range(start+gap,len(nlist),gap):

        current_value = nlist[i]
        position = i

        while position>=gap and nlist[position-gap]>current_value:
            nlist[position]=nlist[position-gap]
            position = position-gap

        nlist[position]=current_value


nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist)

Sample Output:

After increments of size 4 The list is [14, 41, 43, 21, 57, 46, 45, 27, 70]                                   
After increments of size 2 The list is [14, 21, 43, 27, 45, 41, 57, 46, 70]                                   
After increments of size 1 The list is [14, 21, 27, 41, 43, 45, 46, 57, 70]                                   
[14, 21, 27, 41, 43, 45, 46, 57, 70]

 

Write a Python program to sort a list of elements using shell sort algorithm

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.