选择排序
1:基本介绍
1.1:概念
在待排序的数据内,按照一定的规则找到最大或者最小的数据,然后交换到指定的位置,在不断缩小待排序数据的范围直到结束为止。
1.2:步骤

2:代码实现
package sort; public class SelectSortTest { public static void main(String[] args) { // TODO Auto-generated method stub int[] array = new int[] { 9,8,7,6,5,4,3,2,1,0 }; System.out.println("排序前的序列:"); for(int i:array) { System.out.print(i); } SelectSort ss = new SelectSort(array); ss.startSort(); System.out.println(""); System.out.println("排序后的序列:"); for(int i:array) { System.out.print(i); } } } class SelectSort { //时间复杂度为O(n^2) private int tempMin ;//定义变量temp存放最小数据 private int tempI ;//定义变量temp存放最小数据位置 private int temp;//用来作为最小数据tempMin和当前位置做交换的中间缓存 private boolean flag;//是否进行过交换的标志?false代表没有交换过,true则代表交换过 private int[] array;//待排序的数组 private int length;//待排序的数组长度 public SelectSort(int[] a) { this.array = a; this.tempMin = 0; this.tempI = 0; this.flag = false; this.length = array.length; } public void startSort() {//从小到大 for(int i=0;i<length-1;i++) { if(i==length-2) { System.out.println(i+" "); } this.tempMin= this.array[i]; for(int j=i;j<length;j++) { if(array[j]<tempMin) { this.tempMin = array[j];//找打序列中最小的一项,保存其值和位置 this.tempI = j; } } this.temp = this.array[i];//进行交换 this.array[i] = this.tempMin; this.array[tempI] = this.temp; } } }

浙公网安备 33010602011771号