zoukankan      html  css  js  c++  java
  • 大话数据结构(15) 排序算法(2) (简单选择排序)

    本文根据《大话数据结构》一书,实现了Java版的简单选择排序

    更多:数据结构与算法合集 

    基本思想

      简单选择排序很简单,顾名思义,即在无序序列中,每一轮选取出最小的值作为有序序列的第i个记录。

    完整Java代码

    (含测试代码)

    import java.util.Arrays;
    
    /**
     * 
     * @Description 简单选择排序
     *
     * @author yongh
     * @date 2018年9月15日 上午11:04:36
     */
    public class SelectSort {
    	/**
    	 * 简单选择排序
    	 */
    	public void selectSort(int[] arr) {
    		if (arr == null || arr.length <= 1)
    			return;
    		for (int i = 0; i < arr.length - 1; i++) {
    			int min = i; // 最小值的下标
    			for (int j = i + 1; j <= arr.length - 1; j++) {
    				if (arr[j] < arr[min])
    					min = j;
    			}
    			swap(arr, min, i);
    		}
    	}
    
    	public void swap(int[] a, int i, int j) {
    		int temp;
    		temp = a[j];
    		a[j] = a[i];
    		a[i] = temp;
    	}
    
    	// =========测试代码=======
    	public void test1() {
    		int[] a = null;
    		selectSort(a);
    		System.out.println(Arrays.toString(a));
    	}
    
    	public void test2() {
    		int[] a = {};
    		selectSort(a);
    		System.out.println(Arrays.toString(a));
    	}
    
    	public void test3() {
    		int[] a = { 1 };
    		selectSort(a);
    		System.out.println(Arrays.toString(a));
    	}
    
    	public void test4() {
    		int[] a = { 3, 3, 3, 1, 2, 1, 3, 3 };
    		selectSort(a);
    		System.out.println(Arrays.toString(a));
    	}
    
    	public void test5() {
    		int[] a = { -3, 6, 3, 1, 3, 7, 5, 6, 2 };
    		selectSort(a);
    		System.out.println(Arrays.toString(a));
    	}
    
    	public static void main(String[] args) {
    		SelectSort demo = new SelectSort();
    		demo.test1();
    		demo.test2();
    		demo.test3();
    		demo.test4();
    		demo.test5();
    	}
    }
    

      

    null
    []
    [1]
    [1, 1, 2, 3, 3, 3, 3, 3]
    [-3, 1, 2, 3, 3, 5, 6, 6, 7]
    SelectSort

    复杂度分析

      简单选择排序的特点是交换移动次数相当少,可以节约相应的时间

      比较次数:Σ(n-i)=n(n-1)/2次,所以时间复杂度为O(n^2)。虽然时间复杂度相同,但快速选择排序的性能还是略优于冒泡排序

    更多:数据结构与算法合集 

  • 相关阅读:
    Linux 基础命令(一)转
    Django项目发布 环境部署(下)
    Django项目发布 环境部署(中)
    Django项目发布 环境部署(上)
    deepin linux 打开ssh服务
    虚拟机网卡重启
    centos7 mysql数据库安装和配置
    centos7 修改网络配置
    MySQL----view & transaction
    MySQL ----函数
  • 原文地址:https://www.cnblogs.com/yongh/p/9683818.html
Copyright © 2011-2022 走看看