This preview shows page 1. Sign up to view the full content.
Unformatted text preview: al
3)+
n(n Notice that we haven't said anything about
Notice
average performance.
average
Selection sort always involves n(n1)/2
1)/2
comparisons.
comparisons.
This occurs even if the array was sorted already.
Not very good.
Maybe we should try to speed this up. Applied Programming
Applied Before we do, why is this not as good?
Before
why Applied Programming Bubble Sort
This involves the same number of passes but
This
more moves (selection sort involved less than n).
more
Sounds worse. We'll see. for (i=0;i<n1;i++)
{
for (j=i+1;j<n;j++)
{
if (X[i] > X[j])
{
temp = X[i];
X[i] = X[j];
X[j] = temp;
}
}
} On each outer loop pass, consecutive values in
On
the array are compared and swapped if in the
wrong order.
wrong Because we have to swap too often – adds to the
Because
adds
number of operations we have to perform.Programming
number
Applied After each pass
one extra value is guaranteed to be in its correct
one
position (at the upper end of the array)
position
So only n1 passes will be needed Big values 'bubble up' the array.
Applied Programming for (i=n1;i>0;i)
{
for (j=0;j<i;j++)
if (X[j] > X[j+1])
swap values j and j+1
} Same number of comparisons as selection sort
Same
but a whole lot more swaps.
but There are our guarantees. Note that the variable i iindicates the highest
ndicates
Note
position in the array which is yet to be sorted.
position
We can rewrite code to reflect. Let's look at the code. Applied Programming Applied Programming for (i=n1;i>0;i)
{
for (j=0;j<i;j++)
if (X[j] > X[j+1])
swap values j and j+1
}
LastUnsorted = n1;
while (LastUnsorted > 0)
{
for (j=0;j<LastUnsorted;j++)
if (X[j] > X[j+1])
swap values j and j+1
LastUnsorted;
} If there was a point in the inner loop after which
If
no swapping was performed, then those
remaining entries in the array must be sorted.
remaining
Call that value LastSwapIndex.
Call
LastSwapIndex
LastUnsorted = n1;
while (LastUnsorted > 0)
{
for (j=0;j<LastUnsorted;j++)
if (X[j] > X[j+1])
swap values j and j+1
LastUnsorted;
} Applied Programming
Applied LastUnsorted = n1;
while (LastUnsorted > 0)
{
LastSwapIndex = 0;
for (j=0;j<LastUnsorted;j++)
{
if (X[j] > X[j+1])...
View
Full
Document
This document was uploaded on 04/07/2014.
 Spring '14
 Sort

Click to edit the document details