It is the first algorithm to improve an insertion sort. Its idea was to avoid the large amount of data movement, first by comparing elements that were far apart and then by comparing elements that were less far apart and so on, gradually shinking toward the basic insertion sort.
The algorithm first sorts the elements that are far away and then subsequently reduces the gap between the elements. This gap is also known as intervals. The interval between the elements is reduced based on the sequence used. The performance of the shell sort depends on the type of sequence used for a given input array. Some of the optimal sequences that can be used in the shell sort algorithm are:
1. Shell's original sequence: N/2 , N/4 , …, 1 2. Knuth's increments: 1, 4, 13, …, (3k – 1) / 2 3. Hibbard's increments: 1, 3, 7, 15, 31, 63, 127, 255, 511… and so on.
#shellSort.pydef shellSort(arr): size = len(arr) gap = size//2 while gap > 0: for j in range(gap, size): i = j - gap while i >= 0: if arr[i+gap] >= arr[i]: break else: arr[i], arr[i+gap] = arr[i+gap], arr[i] i -= gap gap //= 2arr = [23, 21, 15, 19, 31, 7, 9, 5, 2]print("Unsorted Array: ",arr)shellSort(arr)print("Sorted Array: ", arr)
function shellSort(arr) { let size = arr.length let gap = Math.floor(size / 2) while (gap > 0) { for (let j = gap; j < size; j++) { for (let i = j - gap; i >= 0; i -= gap) { if (arr[i + gap] >= arr[i]) break else[arr[i + gap], arr[i]] = [arr[i], arr[i + gap]] } } gap = Math.floor(gap / 2) } return arr}let arr = [23, 21, 15, 19, 31, 7, 9, 5, 2]console.log(`Unsorted Array: ${arr}`)arr = shellSort(arr)console.log(`Sorted Array: ${arr}`)