Sorting Notes
Sorting Notes
I. Counting sort ↳
Searching in sorted list gives us tremendous improvement
2. Selection Sort in efficiency
3. Bubble sort
4. Insertion sort
Countingsort
Problem :
Given an
array
of numbers between
,
0 to MAX
↳
scan through this input array and count how many times each number appears
-
Use another array of size MAX -11 ( call this frequency array) to keep track of counts
Once loop through frequency and put elements back into output
-
done , array
g)
""" " "" the
code
i
fi
appears
is
max
i. Total no .
of times is
¥0 fi
Runnigimefwntingsrt :
③ Informal Approach :
storing sorted numbers into output , there are n numbers , so takes Ocn) time
^
Formal :
explanation .
corresponds to total number of times each number appears in input
•
• • 0 Cntn + MAX) =
0Gt MAX)
Selectionsort
→
repeatedly finds max .
element and move it to the back of the array .
} through the
run code
visually .
Selectionsortvscountingsort
counting sort → linear algorithm
→
assumes that input numbers will fall within certain range
→
only efficient if MAX is small
numben.Yseleetionsor.tn/ormax
i thought counting sort is for freq of
goring ? ? ?
→
does not assume
range of input numbers number
→ it is a
wmpurisonsurt as it compares the input numbers during sorting
→ more general 4 wider range of application .
BubbleSort_
→ look at adjacent pairs ,
and swap until they are in order
e. g. Roundly
8
- -
4 23 42 16 is ← swap Time taken : Since ith pass scans through n -
i elements , 7
4 8 23 42 lb 15 there
- -
are n passes in total , same as
4 8
-
23
-
42 lb IS selection sort , 01m£
4 8 Is ← swap
23
-42 -16
← swap
4 8 23 16
-42 I
4 8 23 If 15 42
↳ in place how
Roundly
4 8 23 16 IS 42
- -
4 8 23 16 IS 42
- -
4 8 23 lb IS 42 ← swap
- -
4 8 42 ← swap
16 23 IS
- -
✗
in place now
n :S
last a-
4
bubble -
pass
= ( 4, a)
ali ]
swap
>
aci-D-grepeartt.tl
€4 c-
Insertionsort ① ②
→ partition into 2 :
sorted 4 unsorted partition .
take first element of unsorted partition , find its rightful
③
position in the sorted list ,
insert it there
ue.at#/
inst to represent
shift elements in sorted partition to right till
8/4 23 42 lb IS we find rightful place for I
2
/
%%%"°%°
4 8 23 42 lb 15
✗
Position
4 8 23 42/16 IS ① ② ③ ④ ⑤ ⑥
4 8 23 42 15
4 8 lb 23 42/15 ✓
4 8 15 16 23 42
Curr
-
I
Curr)
insert la ,