You are on page 1of 3

Bubble sort

Sort(r, lo, up)


ArrayToSort r;
int lo, up;

{
int i, j;
while (up>lo)
{
j = lo;
for ( i=lo; i r[i+1].k ) {
exchange( r, i, i+1 );
j = i;}
up = j;
for ( i=up; i>lo; i-- )
if ( r[i].k < r[i-1].k ) {
exchange( r, i, i-1 );
j = i;}
lo = j;
}
}
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest num
ber to greatest number using bubble sort algorithm. In each step, elements writt
en in bold are being compared.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements,
and swaps them.
(1 5 4 2 8) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8
> 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) ( 1 4 2 5 8 )
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is compl
eted. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.
Insertion sort
sort( r, lo, up )
ArrayToSort r;
int lo, up;
{int i, j;
while (up>lo) {
j = lo;
for ( i=lo; i r[i+1].k ) {
exchange( r, i, i+1 );
j = i;}
up = j;
for ( i=up; i>lo; i-- )
if ( r[i].k < r[i-1].k ) {
exchange( r, i, i-1 );
j = i;}
lo = j;
}
}
Merge sort
list sort( n )
int n;
{
list fi, la, temp;
extern list r;
if ( r == NULL ) return( NULL );
else if ( n>1 )
return( merge( sort( n/2 ), sort( (n+1)/2 )));
else {
fi = r; la = r;
/*** Build list as long as possible ***/
for ( r=r->next; r!=NULL; )
if ( r->k >= la->k ) {
la->next = r;
la = r;
r = r->next;
}
else if ( r->k <= fi->k ) {
temp = r;
r = r->next;
temp->next = fi;
fi = temp;
}
else break;
la->next = NULL;
return( fi );
}
};
heap sort
sort( r, lo, up )
ArrayToSort r;
int lo, up;
{int i;
/*** construct heap ***/
for ( i=up/2; i>1; i-- ) siftup(r,i,up);
/*** repeatedly extract maximum ***/
for ( i=up; i>1; i-- ) {
siftup(r,1,i);
exchange( r, 1, i );
}
};
Quick sort

sort( r, lo, up )
ArrayToSort r;
int lo, up;
{int i, j;
ArrayEntry tempr;
while ( up>lo ) {
i = lo;
j = up;
tempr = r[lo];
/*** Split file in two ***/
while ( i tempr.k; j-- );
for ( r[i]=r[j]; i<=tempr.k; i++ );
r[j] = r[i];
}
r[i] = tempr;
/*** Sort recursively, the smallest first ***/
if ( i-lo < up-i ) { sort(r,lo,i-1); lo = i+1; }
else { sort(r,i+1,up); up = i-1; }
}
}

You might also like