# Sort - package DataStructures A class that contains several...

This preview shows pages 1–3. Sign up to view the full content.

package DataStructures; /** * A class that contains several sorting routines, * implemented as static methods. * Arrays are rearranged with smallest item first, * using compareTo. * @author Mark Allen Weiss */ public final class Sort { /** * Simple insertion sort. * @param a an array of Comparable items. */ public static void insertionSort( Comparable [ ] a ) { int j; /* 1*/ for( int p = 1; p < a.length; p++ ) { /* 2*/ Comparable tmp = a[ p ]; /* 3*/ for( j = p; j > 0 & tmp.compareTo( a[ j - 1 ] ) /* 4*/ a[ j ] = a[ j - 1 ]; /* 5*/ a[ j ] = tmp; } } /** * Shellsort, using Shell's (poor) increments. * @param a an array of Comparable items. */ public static void shellsort( Comparable [ ] a ) { int j; /* 1*/ for( int gap = a.length / 2; gap > 0; gap /= 2 ) /* 2*/ for( int i = gap; i < a.length; i++ ) { /* 3*/ Comparable tmp = a[ i ]; /* 4*/ tmp.compareTo( a[ j - gap ] ) < 0; j -= gap ) /* 5*/ a[ j ] = a[ j - gap ]; /* 6*/ a[ j ] = tmp; } } /** * Standard heapsort. * @param a an array of Comparable items. */ public static void heapsort( Comparable [ ] a ) { /* 1*/ for( int i = a.length / 2; i >= 0; i-- ) /* buildHeap */ /* 2*/ percDown( a, i, a.length ); /* 3*/ for( int i = a.length - 1; i > 0; i-- ) { /* 4*/ swapReferences( a, 0, i ); /* deleteMax */

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
/* 5*/ percDown( a, 0, i ); } } /** * Internal method for heapsort. * @param i the index of an item in the heap. * @return the index of the left child. */ private static int leftChild( int i ) { return 2 * i + 1; } /** * Internal method for heapsort that is used in * deleteMax and buildHeap. * @param a an array of Comparable items. * @index i the position from which to percolate down. * @int n the logical size of the binary heap. */ private static void percDown( Comparable [ ] a, int i, int n ) { int child; Comparable tmp; /* 1*/ for( tmp = a[ i ]; leftChild( i ) < n; i = child ) { /* 2*/ child = leftChild( i ); /* 3*/ /* 4*/ child++; /* 5*/ if( tmp.compareTo( a[ child ] ) < 0 ) /* 6*/ a[ i ] = a[ child ]; else /* 7*/ break; } /* 8*/ a[ i ] = tmp; } /** * Mergesort algorithm. * @param a an array of Comparable items.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 7

Sort - package DataStructures A class that contains several...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online