选择排序:也是和冒泡排序一样,作为排序算法的必学入门算法之一。

排序原理:
1.每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个索引处的值,则假定其他某个索引出的值为最小值,最后可以找到最小值所在的索引
2.交换第一个索引处和最小值所在的索引处的值
可以理解为每次遍历,选择出最小元素,把他放在数据的最前面,再同样的操作一直执行。直到最后排序完成!!

图示:

代码实现:

 public static void selectSort(int [] arr){
   
	    if (arr == null || arr.length < 2) {
   
        return;
                }
          for(int i=0;i<arr.length-1;i++){
   
			int minIndex = i;
			for(int j=i+1;j<arr.length;j++){
   
			 minIndex = arr[j] < arr[minIndex] ? j : minIndex;
			}
			 swap(arr, i, minIndex);
		}
		 public static void swap(int[] arr, int i, int j) {
   
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
  		  }
	}

API设计:

package 排序类算法;
/* *@Author:Tstr *@Date:2020/8/15 12:36 *@from:lenovo *@e-mail:x20135201314boy@126.com */
public class MySelectionSort {
   

    public static void sort(Comparable[] a) {
   
        for (int i = 0; i <= a.length - 2; i++) {
   
            //定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素所在的位置
            int minIndex = i;
            for (int j = i + 1; j < a.length; j++) {
   
                //需要比较最小索引minIndex处的值和j索引处的值;
                if (compare(a[minIndex], a[j])) {
   
                    minIndex = j;
                }
            }

            //交换最小元素所在索引minIndex处的值和索引i处的值
            swop(a, i, minIndex);
        }
    }

    /* 比较x元素是否大于y元素 */
    private static boolean compare(Comparable x, Comparable y) {
   
        return x.compareTo(y) > 0;
    }

    /* 数组元素i和j交换位置 */
    private static void swop(Comparable[] a, int i, int j) {
   
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

测试:

package 排序类算法;/* *@Author:Tstr *@Date:2020/8/15 12:47 *@from:lenovo *@e-mail:x20135201314boy@126.com */
import java.util.Arrays;
public class MySelectionTest {
   
    public static void main(String[] args) {
   
        Integer[] testarr = {
   4,6,8,7,9,2,-10,1};
       MySelectionSort.Sort(testarr);
        System.out.println(Arrays.toString(testarr));
    }
}

测试结果:

复杂度分析:
选择排序使用了双层for循环,其中外层循环完成了数据交换,内层循环完成了数据比较,所以我们分别统计数据
交换次数和数据比较次数:
数据比较次数: (N-1)+(N-2)+(N-3)+…+2+1=((N-1)+1)*(N-1)/2=N^2/2-N/2;
数据交换次数: N-1
时间复杂度:N2/2-N/2+(N-1)=N2/2+N/2-1;
根据大O推导法则,保留最高阶项,去除常数因子时间复杂度为O(N^2);
声明:文中涉及图片来自网络,如有侵权,请联系博主删除!
**end----------------------------------------------------------------------------------------- **