220 likes | 327 Views
오진오 Jinoh Oh. CSED101 Introduction to Computing Sorting 1. Sorting. Ascending sort 1, 2, 3, 4, … Descending sort 10, 9, 8, … Greedy approach Selection sort Insertion sort Divide-and-conquer approach Merge sort Quick sort. Selection Sort. 6. 3. 5. 1. 2. 4. 8. 7. 9.
E N D
오진오 Jinoh Oh CSED101 Introduction to ComputingSorting 1
Sorting • Ascending sort • 1, 2, 3, 4, … • Descending sort • 10, 9, 8, … • Greedy approach • Selection sort • Insertion sort • Divide-and-conquer approach • Merge sort • Quick sort
Selection Sort 6 3 5 1 2 4 8 7 9
Selection Sort 6 3 5 1 2 4 8 7 9 1 6 3 5 2 4 8 7 9
Selection Sort 6 3 5 1 2 4 8 7 9 1 6 3 5 2 4 8 7 9 1 2 6 3 5 4 8 7 9
Selection Sort 6 3 5 1 2 4 8 7 9 1 6 3 5 2 4 8 7 9 1 2 6 3 5 4 8 7 9 1 2 3 6 5 4 8 7 9
Selection Sort 6 3 5 1 2 4 8 7 9 1 6 3 5 2 4 8 7 9 1 2 6 3 5 4 8 7 9 1 2 3 6 5 4 8 7 9 1 2 3 4 6 5 8 7 9
Sorting – greedy approach – selection sort • Input: a list of numbers (source list), x1, x2, …, xn • Output: a list of sorted numbers (target list) • Procedure • Pick the smallest number from the source list • Put it to the end of the target list. • Repeat this until the source list becomes empty.
Find_min • Function that find smallest element from given list. • Returns min element and remain list.
Find_min let rec find_ min l = match l with | h::[] -> (h,[]) | h::t -> let (m, l') = find_min t in if h < m then (h, t) else (m, h::l');;
Selection Sort • Function process
Selection Sort let recselection_sort l = match l with | [] -> [] | _ -> let (m, l') = find_min l in m :: (selection l');;
Insertion Sort 6 3 5 1 2 4 8 7 9
Insertion Sort 6 3 5 1 2 4 8 7 9 6 3 5 1 2 4 8 7 9
Insertion Sort 6 3 5 1 2 4 8 7 9 6 3 5 1 2 4 8 7 9 3 6 5 1 2 4 8 7 9
Insertion Sort 6 3 5 1 2 4 8 7 9 6 3 5 1 2 4 8 7 9 3 6 5 1 2 4 8 7 9 3 5 6 1 2 4 8 7 9
Insertion Sort 6 3 5 1 2 4 8 7 9 6 3 5 1 2 4 8 7 9 3 6 5 1 2 4 8 7 9 3 5 6 1 2 4 8 7 9 1 3 5 6 2 4 8 7 9
Sorting – greedy approach – insertion sort • Input: a list of numbers (source list), x1, x2, …, xn • Output: a list of sorted numbers (target list) • Procedure • Pick the first element from the source list • Put it to the proper position of the target list. • Repeat this until the source list becomes empty.
insert • Function to put a element to the proper position of the target list. • Ex) insert 5 [1; 3; 4; 6; 7; 9];; • - : int list = [1; 3; 4; 5; 6; 7; 9]
insert let rec insert x inlist = match inlist with | [] -> [x] | h::t -> if h < x then h :: insert x t else x::h::t ;;
Insertion Sort • Process insertion sort using the insert function. • Ex) insertion [3; 9; 4; 6; 7; 1];; • - : int list = [1; 3; 4; 6; 7; 9]
Insertion Sort • let recinsertion_sort l = match l with [] -> [] | h::t -> insert h (insertion_sort t);;