Browse Source

Add shellsort

parent
commit
34af7910c3
1 changed files with 28 additions and 3 deletions
  1. 28
    3
      sorting.py

+ 28
- 3
sorting.py View File

53
 	#definan el algoritmo de ordenamiento quicksort
53
 	#definan el algoritmo de ordenamiento quicksort
54
 	return lista
54
 	return lista
55
 
55
 
56
-def shellSort(lista):
57
-	#definan el algoritmo de ordenamiento shellsort
58
-	return lista
56
+# inplace
57
+# complexity: O(N^2)
58
+def shellSort(lst):
59
+    # initial gap
60
+    gap = len(lst)
61
+
62
+    while 0 < gap:
63
+        # sort every sublist with given gap
64
+        for start in range(gap):
65
+            f = range(start, len(lst), gap)
66
+            s = range(start + gap, len(lst), gap)
67
+
68
+            # bubble sort on sublist
69
+            swapped = True
70
+            while swapped:
71
+                swapped = False
72
+
73
+                # iterate through every adjacent pair in sublist
74
+                for c, n in zip(f, s):
75
+                    if lst[n] < lst[c]:
76
+                        lst[c], lst[n] = lst[n], lst[c]
77
+                        swapped = True
78
+
79
+        # reduce gap towards 0
80
+        gap = gap // 2
81
+
82
+    return lst
83
+
59
 
84
 
60
 # timeCode function/thunk -> (duration, return value)
85
 # timeCode function/thunk -> (duration, return value)
61
 # measures the time it takes for a function/thunk to return
86
 # measures the time it takes for a function/thunk to return