In | Python3 program for the above approach ; Calculating next gap ; Function for swapping ; Merging the subarrays using shell sorting Time Complexity : O ( nlog n ) Space Complexity : O ( 1 ) ; merge sort makes log n recursive calls and each time calls merge ( ) which takes nlog n steps Time Complexity : O ( n * log n + 2 ( ( n / 2 ) * log ( n / 2 ) ) + 4 ( ( n / 4 ) * log ( n / 4 ) ) + ... . . + 1 ) Time Complexity : O ( logn * ( n * log n ) ) i . e . O ( n * ( logn ) ^ 2 ) Space Complexity : O ( 1 ) ; Calculating mid to slice the array in two halves ; Recursive calls to sort left and right subarrays ; UTILITY FUNCTIONS Function to pran array ; Driver Code
import math NEW_LINE def nextGap ( gap ) : NEW_LINE INDENT if gap <= 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return int ( math . ceil ( gap / 2 ) ) NEW_LINE DEDENT def swap ( nums , i , j ) : NEW_LINE INDENT temp = nums [ i ] NEW_LINE nums [ i ] = nums [ j ] NEW_LINE nums [ j ] = temp NEW_LINE DEDENT def inPlaceMerge ( nums , start , end ) : NEW_LINE INDENT gap = end - start + 1 NEW_LINE gap = nextGap ( gap ) NEW_LINE while gap > 0 : NEW_LINE INDENT i = start NEW_LINE while ( i + gap ) <= end : NEW_LINE INDENT j = i + gap NEW_LINE if nums [ i ] > nums [ j ] : NEW_LINE INDENT swap ( nums , i , j ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT gap = nextGap ( gap ) NEW_LINE DEDENT DEDENT def mergeSort ( nums , s , e ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE mergeSort ( nums , s , mid ) NEW_LINE mergeSort ( nums , mid + 1 , e ) NEW_LINE inPlaceMerge ( nums , s , e ) NEW_LINE DEDENT def printArray ( A , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 11 , 13 , 5 , 6 , 7 ] NEW_LINE arr_size = len ( arr ) NEW_LINE mergeSort ( arr , 0 , arr_size - 1 ) NEW_LINE printArray ( arr , arr_size ) NEW_LINE DEDENT