Browse Source

Implementation of MergeSort algorithm -Carla Ramos

Carla Ramos 2 years ago
parent
commit
fc259adbfe
1 changed files with 39 additions and 1 deletions
  1. 39
    1
      sorting.py

+ 39
- 1
sorting.py View File

@@ -6,12 +6,50 @@ La variable largoLista define el largo de las listas a ordenar
6 6
 La variable veces define las veces que se va a hacer el ordenamiento 
7 7
 Al final se imprimen los promedios de cada algortimo
8 8
 """
9
+from heapq import merge
9 10
 from random import randint
10 11
 import time
11 12
 
13
+
12 14
 def mergeSort(lista):
13 15
 	#definan el algoritmo de ordenamiento mergesort
14
-	return lista
16
+
17
+	# check if the array has more than one element
18
+    if len(lista) > 1:
19
+        # divide the array in two halves
20
+        middle = len(lista)//2
21
+        leftHalf = lista[:middle]
22
+        rightHalf = lista[middle:]
23
+        
24
+        mergeSort(leftHalf)
25
+        mergeSort(rightHalf)
26
+        # declare pointers
27
+
28
+        i = j = k = 0
29
+
30
+        while i < len(leftHalf) and j < len(rightHalf):
31
+            if leftHalf[i] < rightHalf[j]:
32
+                lista[k] = leftHalf[i]
33
+                i = i + 1
34
+
35
+            else:
36
+                lista[k] = rightHalf[j]
37
+                j = j + 1
38
+           
39
+            k = k + 1
40
+
41
+        # continue updating array grabbing any elements that were left
42
+        while i < len(leftHalf):
43
+            lista[k] = leftHalf[i]
44
+            i = i + 1
45
+            k = k + 1
46
+
47
+        while j < len(rightHalf):
48
+            lista[k] = rightHalf[j]
49
+            j = j + 1
50
+            k = k + 1
51
+
52
+    return lista
15 53
 
16 54
 def heapSort(lista):
17 55
 	#definan el algoritmo de ordenamiento heapsort