The last one is called the "selection sorting", it is probably the most efficient one.
/**
* This is the array related package.
*/
package array;
import exception.ArrayException;
/**
* Demonstrates the selection sort array.
* @author Jiafan Zhou
*/
public class SelectionSortArray
{
private long[] array;
private int nElements;
/**
* Constructor of this Selection Sort Array application.
* @param max the max items in this array.
*/
public SelectionSortArray(int max)
{
array = new long[max];
nElements = 0;
}
/**
* Insert the value into the array.
* @param value the inserted value
* @exception ArrayException when array is full in size
*/
public void insert(long value) throws ArrayException
{
if (dataSize() == arraySize())
{
throw new ArrayException("This array is full in size.");
}
array[nElements++] = value;
}
/**
* This is a linear search.
* Try to find the specified value in this array.
* @param searchKey search value
* @return true if found, false otherwise
*/
public boolean find(long searchKey)
{
for (int i = 0; i < nElements; i++)
{
if (array[i] == searchKey)
{
return true;
}
}
return false;
}
/**
* Try to delete the specified value in this array.
* If the value is deleted successfully, the old value
* will be replaced as a 0.
* @param value the value to be deleted
* @return true if deleted sucessfully, false otherwise.
*/
public boolean delete(long value)
{
for (int i = 0; i < nElements; i++)
{
if (array[i] == value)
{
for (int j = i; j < nElements - 1; j++)
{
array[j] = array[j + 1];
}
array[nElements - 1] = 0;
nElements--;
return true;
}
}
return false;
}
/**
* Return the size of this array.
* @return the size of this fixed array.
*/
public int arraySize()
{
return array.length;
}
/**
* Return the elements this array contained.
* @return the elements of this array contained.
*/
public int dataSize()
{
return nElements;
}
/**
* Clear all the elements in this array.
*/
public void clear()
{
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
}
/**
* Displays array contents.
* @return displays array contents
*/
@Override
public String toString()
{
String string = "";
for (long i : array)
{
string += (i + " ");
}
return string;
}
/**
* This is a selection sort(ascending).
*/
public void ascendingSort()
{
int minIndex;
for (int i = 0; i < nElements - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < nElements; j++)
{
if (array[j] < array[minIndex])
{
minIndex = j;
}
}
long temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
/**
* This is a selection sort(descending).
*/
public void descendingSort()
{
int maxIndex;
for (int i = 0; i < nElements - 1; i++)
{
maxIndex = i;
for (int j = i + 1; j < nElements; j++)
{
if (array[j] > array[maxIndex])
{
maxIndex = j;
}
}
long temp = array[i];
array[i] = array[maxIndex];
array[maxIndex] = temp;
}
}
}