Open In App

Python Program for ShellSort

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h\’th element is sorted. 

Python Program for ShellSort

The provided Python code demonstrates Shell Sort, an optimization of the Insertion Sort algorithm. Shell Sort sorts elements in larger intervals initially, gradually reducing the interval size. The code defines the shellSort function that takes an array arr as input. It initializes a gap size gap as half the length of the array. The algorithm performs a modified insertion sort within each interval, gradually reducing the gap. Elements are compared and shifted to their correct positions. The driver code initializes an array, applies the shellSort function, and prints both the original and sorted arrays. This algorithm’s time complexity depends on the chosen gap sequence, offering improved performance over Insertion Sort.

Python




# Python program for implementation of Shell Sort
 
def shellSort(arr):
 
    # Start with a big gap, then reduce the gap
    n = len(arr)
    gap = n/2
 
    # Do a gapped insertion sort for this gap size.
    # The first gap elements a[0..gap-1] are already in gapped
    # order keep adding one more element until the entire array
    # is gap sorted
    while gap > 0:
 
        for i in range(gap,n):
 
            # add a[i] to the elements that have been gap sorted
            # save a[i] in temp and make a hole at position i
            temp = arr[i]
 
            # shift earlier gap-sorted elements up until the correct
            # location for a[i] is found
            j = i
            while j >= gap and arr[j-gap] >temp:
                arr[j] = arr[j-gap]
                j -= gap
 
            # put temp (the original a[i]) in its correct location
            arr[j] = temp
        gap /= 2
 
 
# Driver code to test above
arr = [ 12, 34, 54, 2, 3]
 
n = len(arr)
print ("Array before sorting:")
for i in range(n):
    print(arr[i]),
 
shellSort(arr)
 
print ("\nArray after sorting:")
for i in range(n):
    print(arr[i]),


Output

Array before sorting:
12 34 54 2 3 
Array after sorting:
2 3 12 34 54

Time Complexity: O(n2)

Auxiliary Space: O(1)

Please refer complete article on ShellSort for more details!



Previous Article
Next Article

Similar Reads

Python Program for Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term. Examples: Input :n = 5 Output : 2.70833 Input :n = 7 Output : 2.71806 C/C++ Code # Python code to find smallest K-digit # number divisible by X def sumOfSeries(num): # Computing MAX res = 0 fact = 1 for i in range(1, num+1): fact *=
1 min read
Python Program for Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 C/C++ Code # Python program to print a # square matrix in Z form arr = [[4, 5, 6, 8
2 min read
Python Program for Program to calculate area of a Tetrahedron
A Tetrahedron is simply a pyramid with a triangular base. It is a solid object with four triangular faces, three on the sides or lateral faces, one on the bottom or the base and four vertices or corners. If the faces are all congruent equilateral triangles, then the tetrahedron is called regular. The volume of the tetrahedron can be found by using
2 min read
Python Program for Efficient program to print all prime factors of a given number
Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be "2 2 3". And if the input number is 315, then output should be "3 3 5 7". Following are the steps to find all prime factors. 1) While n is divisible by 2, print 2 and divide n by 2. 2) After step 1, n must be
6 min read
Python Program for Program to cyclically rotate an array by one
Write a Python program for a given array, the task is to cyclically rotate the array clockwise by one time. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: arr[] = {5, 1, 2, 3, 4} Input: arr[] = {2, 3, 4, 5, 1}Output: {1, 2, 3, 4, 5} Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.Approach: Assign every element wi
4 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
Python Program to print digit pattern
The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the fir
3 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Python Program for Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. Python Program for Selection SortThe provided Python code demonstrates the Selection Sort algorithm. Selection Sort has a time
2 min read
Python Program for Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Python Program for Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the length is 0 or 1, the function returns immediately as an array with 0 or 1 element is considered already
2 min read