zoukankan      html  css  js  c++  java
  • 排序算法:选择排序

    选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。

    平均时间复杂度:O(n2)

    空间复杂度:O(1) (用于交换和记录索引)

    package cn.hncu;
    
    import java.sql.Timestamp;
    
    public class selectSort {
        public static void main(String[] args) {
            int[] a = new int[10000];
            for(int i=0;i<a.length;i++){
                a[i] = (int)(Math.random()*a.length);
            }
            long startTime = System.currentTimeMillis();//返回以毫秒为单位的当前时间。
            //1 选择排序
            selectSort1(a);
    
            print(a);
            long endTime = System.currentTimeMillis();//返回以毫秒为单位的当前时间。
            System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
    
    
        }
    
    
    
        private static void selectSort1(int[] a) {
            for(int i=0;i<a.length-1;i++){
                int k=i;
                for(int j=i;j<a.length;j++){
                    if(a[k]>a[j]){
                        k=j;//找到最小的值为a[k]
                    }
                }
                if(a[k]!=a[i]){//位运算交换值
                    a[k]=a[k]^a[i];
                    a[i]=a[k]^a[i];
                    a[k]=a[k]^a[i];
                }
            }
        }
    
    
    
        private static void print(int[] a) {
            for(int i=0;i<a.length;i++){
                System.out.print(a[i]+" ");
            }
            System.out.println();
        }
    
    }
    
  • 相关阅读:
    UI Automator Viewer工具的使用
    SQL数据库面试50题(转载)
    Python +selenium+pycharm(Windows)
    python安装及环境变量配置(Windows)
    JDK的安装与环境变量配置
    shell参数
    文件添加行号
    CentOS 7修改UTC为CST
    shell控制超时
    fio笔记
  • 原文地址:https://www.cnblogs.com/webmen/p/5739381.html
Copyright © 2011-2022 走看看