Docsity

Lecture 24: Linear and Bubble Sort Algorithms, Study notes of Computer Science

Partial preview of the text

Download Lecture 24: Linear and Bubble Sort Algorithms and more Study notes Computer Science in PDF only on Docsity!

„^ Previous Lecture:

„^ Acoustic data: frequency computation „^ Touchtone phone

„^ Today’s Lecture:

„^ Search: Linear Search „^ Sort: Bubble Sort and Insertion Sort „^ Efficiency Analysis

„^ Announcements

„^ Prelim 3 will be returned after lecture. Or pick up fromCS1112 consultants in ACCEL during consulting hrs(today after 4pm)

April 16, 2009

Lecture 24

2

Searching for an item in a collection

Is the collection organized?What is the organizing scheme?

Indiana Jones and the Raiders of the Lost Ark

April 16, 2009

Lecture 24

% f is index of first occurrence%^

of value x in vector v. % f is -1 if x not found.k= 1;while

k<=length(v) && v(k)~=x k= k + 1; endif

k>length(v)f= -1; % signal for x not found else

f= k; end

April 16, 2009

Lecture 24

%^

Linear Search % f is index of first occurrence%^

of value x in vector v. % f is -1 if x not found.k= 1;while

k<=length(v) && v(k)~=x k= k + 1; endif

k>length(v)f= -1; % signal for x not found else

f= k; end

v x^

April 16, 2009

Lecture 24

%^

Linear Search % f is index of first occurrence%^

of value x in vector v. % f is -1 if x not found.k= 1;while

k<=length(v) && v(k)~=x k= k + 1; endif

k>length(v)f= -1; % signal for x not found else

f= k; end

v x^

April 16, 2009

Lecture 24

%^

Linear Search % f is index of first occurrence%^

of value x in vector v. % f is -1 if x not found.k= 1;while

k<=length(v) && v(k)~=x k= k + 1; endif

k>length(v)f= -1; % signal for x not found else

f= k; end

v x^

What if

v^ is sorted?

April 16, 2009

Lecture 24

The “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The second “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The second “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The second “bubble” process

Compare adjacent values.Swap if “out of order.”

April 16, 2009

Lecture 24

The second “bubble” process

After two bubble processes, thefirst two components aresorted.Repeatedly apply the bubbleprocess to sort the whole array