详解选择排序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_39443053/article/details/101312224

详解选择排序

        点关注不迷路,欢迎再访!

选择排序算法也是比较简单的排序算法,其思路比较直观。选择排序算法在每一步中选取最小值来重新排列,从而达到排序的目的。

选择排序算法通过算选择和交换来实现排序,其排序流程如下:
1.首先从原始数组中选择最小的1个数据,将其和第1个位置的数据交换。
2.接着从剩下的n-1个数据中选择次小的1个数据,将其和第2个位置的数据交换。
3.然后不断重复上述过程,知道最后两个数据交换完成。至此,便完成了对原始数组的从小到大的排序。

public static void main(String[] args) {
		int [] scores = {6,4,0,7,5,3};
		int index,temp;
		for (int i = 0; i < scores.length-1; i++) {
			index = i;
			for (int j = i+1; j < scores.length; j++) {
				if(scores[j] < scores[index]) {
					index = j;
				}
			}
			
			if(index != i) {     //交换两个数
				temp = scores[i];
				scores[i] = scores[index];
				scores[index] = temp;
			}
			System.out.print("第"+i+"步排序结果:");    //输出每步排序的结果
			
			for (int h = 0; h < scores.length; h++) {
				System.out.print(" "+scores[h]);
			}
			System.out.print("\n");
		}
	}

第0步排序结果: 0 4 6 7 5 3
第1步排序结果: 0 3 6 7 5 4
第2步排序结果: 0 3 4 7 5 6
第3步排序结果: 0 3 4 5 7 6
第4步排序结果: 0 3 4 5 6 7

从上面的例子可以非常直观地了解到选择排序算法地执行过程。选择排序算法在对n个数据进行排序时,无论原始数据有无顺序,都需要进行n-1步的中间排序。
优点:这种排序方法思路简单直观。
缺点:执行的步骤稍长,效率不高。

猜你喜欢

转载自blog.csdn.net/qq_39443053/article/details/101312224
今日推荐