选择排序是一种不稳定排序。每次都选取未排序的序列中最大值或最小值,与第i个数值交换。交换中有可能破坏等数值元素的相对位置。例如: 4 6 4 2 1 第一遍选择会选取‘1’和第一个‘4’交换,则原来第一位的‘4’会排在第三位的‘4’之后。时间复杂度0(n^2)。
算法中需要注意的地方:每次选择极值时先记录当前位置(即要排序的位置),再遍历未排序的序列如有比当前数值大(或小)记录该位置。如果极值位置和当前位置不一致,则调换两位置上的数值。
public class SelectSort
{
public SelectSort(){}
public static int[] sort(int[] array,String rule)
{
if(!rule.equalsIgnoreCase("increase") && !rule.equalsIgnoreCase("decrease"))
{
System.out.println("Please input the right define of rule: [increase] or [decrease]!");
System.exit(-1);
}
int[] arraySorted = array.clone();
for(int i=0;i<arraySorted.length;i++)
{
int index = i;
for(int j=i+1;j<arraySorted.length;j++)
{
if(rule.equalsIgnoreCase("increase"))
{
if(arraySorted[j]<arraySorted[index]) index=j;
}
if(rule.equalsIgnoreCase("decrease"))
{
if(arraySorted[j]>arraySorted[index]) index=j;
}
}
if(index!=i)
{
int temp = arraySorted[i];
arraySorted[i] = arraySorted[index];
arraySorted[index] = temp;
}
}
return arraySorted;
}
private static void print(int[] array)
{
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void main(String[] args)
{
int[] array = new int[]{1,10,3,5,2,6};
int[] arraySort = sort(array,"increase");
System.out.println("Before sort:");
print(array);
System.out.println("After sort:");
print(arraySort);
}
}