Docsity

Insertion Sort - Lecture Slides | CSCE 350, Study notes of Computer Science

Toggle sidebar
bg1
1
CSCE 350:
Data Structures and Algorithms
Chin-Tser Huang
University of South Carolina
02/27/2009 2
Announcement
๎š„Reading assignment: Chapter 5.2
๎š„Homework 3 is returned today
๎š„High 4, Average 3.35
๎š„Homework 4 is assigned on February 25 and
is due on Wednesday, March 4 in class
๎š„Please download it from class website
๎š„Have your answers neatly typed
๎š„Explain your answer clearly and adequately by
showing the steps
02/27/2009 3
Variable-size-decrease
๎š„A size reduction pattern varies from one iteration of an
algorithm to another
๎š„Example: Euclidโ€™s algorithm for computing the greatest
common divisor
gcd(
m
,
n
) = gcd(
n
,
m
mod
n
)
๎š„The arguments on the right-hand side are always
smaller than those on the left-hand side
๎š„But they are not smaller neither by a constant nor by a
constant factor
02/27/2009 4
Insertion Sort
๎š„This is a typical decrease-by-one technique
๎š„Assume
A
[0..
i-
1] has been sorted, how to
achieve the sorted
A
[0..
i
]?
๎š„Solution: insert the last element
A
[
i
] to the right
position
02/27/2009 5
Example
๎š„Sort 89 45 68 90 29 34 17
02/27/2009 6
Pseudocode of Insertion Sort
pf2

Partial preview of the text

Download Insertion Sort - Lecture Slides | CSCE 350 and more Study notes Computer Science in PDF only on Docsity!

CSCE 350:

Data Structures and Algorithms

Chin-Tser Huang

[email protected]

University of South Carolina

02/27/2009 2

Announcement

ย„ Reading assignment: Chapter 5.

ย„ Homework 3 is returned today

ย„ High 4, Average 3.

ย„ Homework 4 is assigned on February 25 and

is due on Wednesday, March 4 in class

ย„ Please download it from class website ย„ Have your answers neatly typed ย„ Explain your answer clearly and adequately by showing the steps

02/27/2009 3

Variable-size-decrease

ย„ A size reduction pattern varies from one iteration of an algorithm to another

ย„ Example: Euclidโ€™s algorithm for computing the greatest common divisor

gcd(m,n) = gcd(n,m modn)

ย„ The arguments on the right-hand side are always smaller than those on the left-hand side ย„ But they are not smaller neither by a constant nor by a constant factor

02/27/2009 4

Insertion Sort

ย„ This is a typical decrease-by-one technique

ย„ AssumeA[0..i-1] has been sorted, how to

achieve the sortedA[0..i]?

ย„ Solution: insert the last elementA[i] to the right

position

02/27/2009 5

Example

ย„ Sort 89 45 68 90 29 34 17

02/27/2009 6

Pseudocode of Insertion Sort

02/27/2009 7

Analysis of Insertion Sort

ย„ Time efficiency

C worst(n) =n(n-1)/2 โˆˆ ฮ˜(n 2 )

C avg(n) โ‰ˆ n 2 /4 โˆˆ ฮ˜(n 2 )

C best(n) =n - 1 โˆˆ ฮ˜(n) (also fast on almost sorted

arrays)

ย„ Space efficiency: in-place

ย„ Stability: yes ย„ Best elementary sorting algorithm overall

ย„ Binary insertion sort