Shell Sort is an in-place comparison-based sorting algorithm that generalizes the insertion sort algorithm to allow the exchange of items that are far apart. It is named after its inventor, Donald Shell, who introduced it in 1959. Shell Sort is more efficient than simple algorithms like bubble sort and insertion sort, particularly for larger lists, due to its improved time complexity.
gap distance apart are compared and swapped if they are in the wrong order.def shell_sort(arr):
n = len(arr)
gap = n // 2
# Start with a big gap, then reduce the gap
while gap > 0:
# Do a gapped insertion sort for this gap size.
# The first gap elements arr[0..gap-1] are already in gapped order
for i in range(gap, n):
temp = arr[i]
j = i
# Shift earlier gap-sorted elements up until the correct location
# for arr[i] is found
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
# Put temp (the original arr[i]) in its correct location
arr[j] = temp
gap //= 2
return arr
# Example usage
arr = [12, 34, 54, 2, 3]
sorted_arr = shell_sort(arr)
print("Sorted array is:", sorted_arr)
def shell_sort(arr):
shell_sort is defined to take a single list arr as its parameter. n = len(arr)
gap = n // 2
n holds the length of the array.gap is initialized to half the length of the array. The gap determines the intervals at which elements are compared and sorted. while gap > 0:
while loop runs as long as gap is greater than 0. The gap is reduced in each iteration, performing gapped insertion sort for each gap size. for i in range(gap, n):
temp = arr[i]
j = i
for loop starts from the element at index gap and runs to the end of the array.temp holds the value of the current element to be compared and inserted.j is initialized to the current index i. while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
while loop compares the current element temp with the element at index j - gap. If temp is smaller, the element at j - gap is shifted to the right.j is decremented by gap to continue comparing and shifting elements. arr[j] = temp
j is less than gap or temp is greater than or equal to arr[j - gap]), the value of temp is inserted at index j. gap //= 2
while loop. return arr
arr is returned.arr = [12, 34, 54, 2, 3]
sorted_arr = shell_sort(arr)
print("Sorted array is:", sorted_arr)
arr is sorted using the shell_sort function, and the sorted list is printed.Sorted array is: [2, 3, 12, 34, 54]