Python Shell Sort

Document 对象参考手册Python3 Examples

Shell sort, also known as the decreasing incremental sort algorithm, is a more efficient improved version of insertion sort. However, Shell sort is an unstable sorting algorithm.

The basic idea of Shell sort is: first divide the entire sequence of records to be sorted into several subsequences and perform direct insertion sort on each subsequence separately. When the records in the entire sequence are "basically ordered", then perform direct insertion sort on all records sequentially.

Example

def shellSort(arr): n = len(arr) gap = int(n/2) while gap > 0: for i in range(gap,n): temp = arr[i] j = i while j >= gap and arr[j-gap] >temp: arr[j] = arr[j-gap] j -= gap arr[j] = temp gap = int(gap/2) arr = [ 12, 34, 54, 2, 3] n = len(arr) print ("Before sorting:") for i in range(n): print(arr[i]), shellSort(arr) print ("\nAfter sorting:") for i in range(n): print(arr[i]),

Executing the above code outputs the following result:

排序前:
12
34
54
2
3

排序后:
2
3
12
34
54

Document 对象参考手册Python3 Examples

Other Extensions