4 Lecture 2 Sorting
4 Lecture 2 Sorting
FALL 2024
Lecture No:02(A)
Input:
Output:
Various
algorithms are better suited to
some of these situations
4
Types of Sorting Algorithms
Internal Sort
– The data to be sorted is all stored in the
computer’s main memory.
External Sort
– Some of the data to be sorted might be
stored in some external, slower, device.
In Place Sort
– The amount of extra space required to sort
the data is constant with the input size.
6
Insertion Sort
7
Insertion Sort
12
8
Insertion Sort
6 10 24 36
12
9
Insertion Sort
6 10 24 3
6
12
10
Insertion Sort
input array
5 2 4 6 1
3
at each iteration, the array is divided in two sub-arrays:
left sub-array right sub-array
sorted unsorted
11
Insertion Sort
12
INSERTION-SORT
Alg.: INSERTION-SORT(A) 1 2 3 4 5 6 7 8
for i ← 2 to n a1 a2 a3 a4 a5 a6 a7 a8
do key ← A[ i ] key
j←i-1
while j > 0 and A[j] > key
do A[j + 1] ← A[j]
j←j–1
A[j + 1] ← key
13 Insertion sort – sorts the elements in place
14
Sorting Algorithms …….. Insertion
Sort
Statement Execution Cost
proc insertionSort(a as array)
n |a| 1
for i 2 to n do n times
key a[i] n-1 times
ji–1 n-1 times
while j > 0 and a[j] > 1 + 2 + 3 + 4 + …. + n times
key do
a[j+1] a[j] 1 + 2 + 3 + 4 + …. +n-1
times
jj-1 1 + 2 + 3 + 4 + …. + n-1
times
next
15 a[j+1] key n-1 times
Sorting Algorithms …….. Insertion
Sort
16
Insertion Sort - Summary
Advantages
– Good running time for “almost sorted”
arrays (n)
Disadvantages
(n2) running time in worst and average
case
n2/2 comparisons and exchanges
17
Summary
19