zoukankan      html  css  js  c++  java
  • 简单排序——冒泡,选择,插入

        // 冒泡排序 每一次内循环将相邻的元素进行比较交换,直到所有元素比较完毕
        public static void bubbleSort(int arr[]) {
            int temp;
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - i - 1; j++) {
                    if (arr[j] > arr[j + 1]) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
        }
    
        // 选择排序 优化后的冒泡排序,
        // 内循环进行比较找出最大或最小元素的坐标;在内循环结束后进行交换
        // 相对冒泡排序来说,优化了内存使用空间
        public static void selectSort(int[] arr) {
            int minBound, temp;
            for (int i = 0; i < arr.length - 1; i++) {
                minBound = i;
                for (int j = i + 1; j < arr.length - 1; j++) {
                    if (arr[j] < arr[minBound]) {
                        minBound = j; // 内循环只负责找出最小或最大值的坐标
                    }
                }
                temp = arr[i]; // 循环结束后进行交换
                arr[i] = arr[minBound];
                arr[minBound] = temp;
            }
        }
    
        /**
         * 插入排序 选定一个顺序。从左至右 或是从右到左, 默认他们已经是有序的数据 在判断数据时 进行交换位置 实现排序功能
         */
        public static void insertSort(int[] arr) {
            int temp;
            for (int i = 1; i < arr.length; i++) {
                for (int j = i; j > 0; j--) {
                    if (arr[j] < arr[j - 1]) {
                        temp = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = temp;
                    }
                }
            }
    
        }

     附插入排序模拟手稿

     

  • 相关阅读:
    启动容器失败:endpoint with name cop already exists in network host.
    docker定时任务执行脚本报错:the input device is not a TTY
    期末总结
    云图学习
    豆瓣top250
    爬取学习
    爬取图片
    爬取学习bs4
    爬取学习 屠戮盗版天堂
    爬取学习
  • 原文地址:https://www.cnblogs.com/shenwenbo/p/8306881.html
Copyright © 2011-2022 走看看