选择排序是每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
选择排序是不稳定的排序方法。
比如初始数组资源 【60 4 20 1 3 16】
第一趟排序后:【16 4 20 1 3】 60
第二趟排序后:【16 4 3 1】 20 60
第三趟排序后:【1 4 3】 16 20 60
第四趟排序后:【1 3】4 16 20 60
第五趟排序后:【1】 3 4 16 20 60
设计过程:
> 在项目中创建类SelectSort,在窗体中添加两个文本框、“生成随机数”和“选择排序”两个按钮;
> 生成随机数:
private int[] array = new int[10];
protected void do_button_actionPerformed(ActionEvent e){
Random random = new Random();
textArea1.setText("");
for(int i =0 ;i<array.length; i++)
{
array[i] = random.nextInt(50);
textArea1.append(arrat[i]+" ");
}
}
> 对随机生成的数组进行排序。并显示到文本框中:
protected void do_button_actionPerformed(ActionEvent e){
textArea2.setText("");
int index;
for(int i =1;i<array.length;i++)
{
index = 0;
for(int j = 1;j<=array.length-i;j++)
{
if(array[j]>array[index]){
index = j;
}
}
int temp = array[array.length - i];
array[array.length -i] = array[index];
array[index] = temp ;
}
for(int i = 0;i <array.length ; i++){
textArea2.append(array[i]+" ");
}
}
心得:选择排序是从数组中挑选最大的数放到最后,而遇到数值相等的值不进行处理,所以,如果数值重复的比较多,建议用选择排序,这样交换的次数比较少,相对的速度将得到提升。
下图是各种排序的比较: