Skip to content

Commit 6ac2c5f

Browse files
committed
Aggiunto materiale sugli algoritmi di ordinamento
1 parent aff269f commit 6ac2c5f

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

scripts/sort_algo.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Wed Nov 15 17:23:55 2017
4+
5+
@author: gualandi
6+
"""
7+
8+
from pairslist import IsEmpty, Min, RemoveFirst, MakeList, MakeRandomInts, Head, Filter, Append
9+
10+
def SelectionSort(As):
11+
""" Semplice implementazione ricorsiva di selection sort """
12+
def SortI(Ls):
13+
if IsEmpty(Ls):
14+
return Ls
15+
a = Min(Ls)
16+
return MakeList(a, SortI(RemoveFirst(Ls, a)))
17+
18+
return SortI(As)
19+
20+
def QuickSort(As, Compare=lambda x,y: x<=y):
21+
""" Semplice implementazione ricorsiva di quick sort """
22+
if IsEmpty(As):
23+
return As
24+
x = Head(As)
25+
# ESERCIZIO: Invece di avere queste due funzioni separate, si potrebbe
26+
# avere un'unica funzione che restituisce le due liste, ma
27+
# "itera" sulla lista As solo una volta invece di due volte
28+
Ls = Filter(lambda z: Compare(z, x), Tail(As))
29+
Gs = Filter(lambda z: not Compare(z, x), Tail(As))
30+
return Append(QuickSort(Ls, Compare), Append(MakeList(x), QuickSort(Gs, Compare)))
31+
32+
def MergeSort(As):
33+
""" Semplice implementazione ricorsiva del merge sort """
34+
# DA FARE COME ESERCIZIO
35+
pass
36+
37+
#-----------------------------------------------
38+
# MAIN function per testare tutte le soluzioni
39+
#-----------------------------------------------
40+
if __name__ == "__main__":
41+
import random
42+
random.seed(13)
43+
Ls = MakeRandomInts(10, 1, 100)
44+
print(Ls)
45+
46+
print('Selection sort:', SelectionSort(Ls))
47+
48+
print('Quick sort:', QuickSort(Ls))
49+
print('Quick sort:', QuickSort(Ls, lambda x,y: x<y))
50+
51+
# Test Di ordinamento di lista di coppie
52+
Ls = (('b',3), (('a',1), (('c',-10), (('r', 13), None))))
53+
print('Quick sort:', QuickSort(Ls, lambda x,y: x[0]<y[0]))
54+
print('Quick sort:', QuickSort(Ls, lambda x,y: x[1]>y[1]))
55+
56+
# ESERCIZIO: Implementare il merge sort
57+
print('Merge sort:', MergeSort(Ls))
58+
59+
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+

slides/Sorting.pdf

762 KB
Binary file not shown.

0 commit comments

Comments
 (0)