Selection Sort
In this algorithm we start at the first element
of the array and go through the array and find the minimum element.
We swap the minimum element with the element at the first place.
We start at the second position in the array and go through the
entire array and find the minimum element in the remaining portion
of the array. We swap that minimum element with the element at the
second position. We start at the third position and repeat the
procedure until we have reached the end of the array.
public static void selectionSort ( int[] anArray )
{
for ( int i = 0; i < anArray.length - 1; i++ )
{
// Find the minimum
int min = anArray[i];
int minIdx = i;
for ( int j = i + 1; j < anArray.length; j++ )
{
if ( anArray[j] < min )
{
min = anArray[j];
minIdx = j;
}
}
// Swap the minimum element with the element at the ith place
anArray[minIdx] = anArray[i];
anArray[i] = min;
}
}
Binary Search
If the array is already sorted use binary search to find an
element in the array. The algorithm was explained in class
and this is the code for it.
public int binarySearch ( int[] a, int x )
{
int low = 0;
int high = a.length - 1;
int mid;
while ( low <= high )
{
mid = ( low + high ) / 2;
if ( x > a[mid] )
low = mid + 1;
else if ( x < a[mid] )
high = mid - 1;
else
return mid; // x == a[mid]
}
// The element does not exist in the array
return (-1);
}
Merge Routine
In this merge routine we assume that the arrays that are passed
to it are of non zero length and sorted in ascending order.
public static int[] merge ( int[] arrayA, int[] arrayB )
{
// Create an array C that will hold all the elements in arrays A and B.
int[] arrayC = new int [ arrayA.length + arrayB.length ];
// Create pointers that will traverse the arrays. The pointers are
// really pointing to the index of the array element that we are visiting
int idxA = 0;
int idxB = 0;
int idxC = 0;
// Compare elements in each array A and B and write out the elements in
// array C
while ( ( idxA < arrayA.length ) && ( idxB < arrayB.length ) )
{
if ( arrayA [idxA] < arrayB [idxB] )
{
arrayC [idxC++] = arrayA [idxA++];
}
else
{
arrayC [idxC++] = arrayB [idxB++];
}
}
// Write out array A if it is not empty
while ( idxA < arrayA.length )
{
arrayC [idxC++] = arrayA [idxA++];
}
// Write out array B if it is not empty
while ( idxB < arrayB.length )
{
arrayC [idxC++] = arrayB [idxB++];
}
return arrayC;
}