/*
* 选择排序的基本思想是:每一躺(例如第i躺,i=0,1,...,n-2)在后面n-i个待排序的元素中
* 选出排序码最小的元素,作为有序元素序列的第i个元素。待到第n-2躺做完,待排序元素只剩下一个
* ,就不用排序了
*
*
*/
public class SelectSort <E extends Comparable<E>>
{
private E[] elementArray;
int length;
public SelectSort(E[] array)
{
elementArray = array;
length = array.length;
}
/*
* 直接选择排序是一种简单的排序方法,它的基本步骤是:
* 1.在一组元素V[i]-V[n-1]中选择具有最小排序码的元素;
* 2.若它不是这组元素中的第一个元素,则将它与这组元素中的第一个元素对调;
* 3.在这组元素中剔除这个具有最小排序码的元素,在剩下的元素V[i+1]-V[n-1]中重复执行第1、2步。直到剩下的元素只有一个为止。
*
*/
public void directSelectSort()
{
for(int i=0;i<length;i++)
{
int minIndex = i;
for(int j=i;j<length;j++)
{
if (elementArray[j].compareTo(elementArray[minIndex])<0)
{
minIndex = j;
}
}
if (minIndex!=i)
{
E temp = elementArray[minIndex];
elementArray[minIndex] = elementArray[i];
elementArray[i] = temp;
}
}
}
public void print()
{
for (int i = 0; i < length; i++)
{
System.out.println(elementArray[i]);
}
}
}
Example for the model:
Integer[] array6 = {36,3,2,2,9,1,4,8};
SelectSort<Integer> test6 = new SelectSort<>(array6);
test6.directSelectSort();
test6.print();
The result of the example:
1
2
2
3
4
8
9
36