Sfoglia il codice sorgente

Add inital shellsort implementation

parent
commit
71b2da84e8
1 ha cambiato i file con 27 aggiunte e 3 eliminazioni
  1. 27
    3
      sorting.py

+ 27
- 3
sorting.py Vedi File

@@ -22,9 +22,33 @@ def quickSort(lista):
22 22
 	#definan el algoritmo de ordenamiento quicksort
23 23
 	return lista
24 24
 
25
-def shellSort(lista):
26
-	#definan el algoritmo de ordenamiento shellsort
27
-	return lista
25
+# inplace
26
+# complexity: O(N^2)
27
+def shellSort(lst):
28
+    # initial gap
29
+    gap = len(lst)
30
+
31
+    while 0 < gap:
32
+        # sort every sublist with given gap
33
+        for start in range(gap):
34
+            f = range(start, len(lst), gap)
35
+            s = range(start + gap, len(lst), gap)
36
+
37
+            # bubble sort on sublist
38
+            swapped = True
39
+            while swapped:
40
+                swapped = False
41
+
42
+                # iterate through every adjacent pair in sublist
43
+                for c, n in zip(f, s):
44
+                    if lst[n] < lst[c]:
45
+                        lst[c], lst[n] = lst[n], lst[c]
46
+                        swapped = True
47
+
48
+        # reduce gap towards 0
49
+        gap = gap // 2
50
+
51
+    return lst
28 52
 
29 53
 # timeCode function/thunk -> (duration, return value)
30 54
 # measures the time it takes for a function/thunk to return