Smalls pivot bigs john edgar 65 usethesamealgorithmto

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ons
to
find
 smallest n‐1 n‐2 … 2 1 0 n(n‐1)/2 John Edgar 43 Java public void selectionSort(int arr){ for(int i = 0; i < arr.length-1; ++i){ int smallest = i; outer
loop
 // Find the index of the smallest element n‐1
times
 for(int j = i + 1; j < arr.length; ++j){ if(arr[j] < arr[smallest]){ smallest = j; inner
loop
body
 } n(n
–
1)/2
times
 } // Swap the smallest with the current item int temp = arr[i];{ arr[i] = arr[smallest]; arr[smallest] = temp; } } John Edgar 44 !  The
outer
loop
is
evaluated
n‐1
times
 The
inner
loop
is
evaluated
n(n
–
1)/2
times
 !  There
are
4
instructions
but
one
is
only
evaluated
some
of
 !  7
instructions
(including
the
loop
statements)
 !  Cost
is
7(n‐1)
 !  !  !  Some
constant
amount
(k)
of
work
is
performed
 Total
cost:
7(n‐1)
+
4(n(n
–
1)/2)
+
k
 !  Assumption:
all
instructions
have
the
same
cost
 John Edgar 45 the
time
 !  Worst
case
cost
is
4(n(n
–
1)/2)
 ▪  e.g.
initializing
the
outer
loop
 !  In
broad
terms
and
ignoring
the
actual
number
of
 executable
statements
selection
sort
 !  Makes
n*(n
–
1)/2
comparisons,
regardless
of
the
original
 !  Neither
of
these
operations
are
substantially
 affected
by
the
organization
of
the
input

 order
of
the
input
 !  Performs
n
–
1
swaps
 John Edgar 46 !  Another
simple
sorting
algorithm
 !  Divides
array
into
sorted
and
unsorted
parts
 !  The
sorted
part
of
the
array
is
expanded
one
 element
at
a
time
 !  Find
the
correct
place
in
the
sorted
part
to
place
 the
1st
element
of
the
unsorted
part
 ▪  By
searching
through
all
of
the
sorted
elements

 !  Move
the
elements
after
the
insertion
point
up
 one
position
to
make
space
 John Edgar 47 23 41 33 81 07 19 11 45 23 41 33 81 07 19 11 45 23 33 41 81 07 19 11 45 23 33 41 81 07 19 11 45 07 23 33 41 81 19 11 45 07 19 23 33 41 81 11 45 07 11 19 23 33 41 81 45 07 11 19 23 33 41 45 81 treats first element as sorted part locate position for 41 - 1 comparison locate position for 33 - 2 comparisons locate position for 81 - 1 comparison locate position for 07 - 4 comparisons locate position for 19- 5 comparisons locate position for 11- 6 comparisons locate position for 45 – 2 comparisons John Edgar 48 Java public void insertionSort(int arr){ for(int i = 1; i < arr.length; ++i){ outer
loop
 int temp = arr[i]; n‐1

times
 in...
View Full Document

This note was uploaded on 04/17/2010 for the course CMPT 11151 taught by Professor Gregorymori during the Spring '10 term at Simon Fraser.

Ask a homework question - tutors are online