Ver código fonte

added quicksort function

Ricardo-gonzalez32 2 anos atrás
pai
commit
05bed1d51e
1 arquivos alterados com 26 adições e 0 exclusões
  1. 26
    0
      sorting.py

+ 26
- 0
sorting.py Ver arquivo

@@ -19,6 +19,32 @@ def heapSort(lista):
19 19
 
20 20
 def quickSort(lista):
21 21
 	#definan el algoritmo de ordenamiento quicksort
22
+	elements = len(lista)
23
+    
24
+    #Base case
25
+	if elements < 2:
26
+		return lista
27
+    
28
+	current_position = 0 #Position of the partitioning element
29
+
30
+	for i in range(1, elements): #Partitioning loop
31
+		if lista[i] <= lista[0]:
32
+			current_position += 1
33
+			temp = lista[i]
34
+			lista[i] = lista[current_position]
35
+			lista[current_position] = temp
36
+
37
+	temp = lista[0]
38
+	lista[0] = lista[current_position] 
39
+	lista[current_position] = temp #Brings pivot to it's appropriate position
40
+    
41
+	left = quickSort(lista[0:current_position]) #Sorts the elements to the left of pivot
42
+	right = quickSort(lista[current_position+1:elements]) #sorts the elements to the right of pivot
43
+
44
+	lista = left + [lista[current_position]] + right #Merging everything together
45
+
46
+	
47
+    
22 48
 	return lista
23 49
 
24 50
 def shellSort(lista):