zoukankan      html  css  js  c++  java
  • 冒泡排序、选择排序、简单二分查找

    1、冒泡排序

      关于冒泡排序,其实就是相邻两两对比,正序反序,大的(小的)往后挪一个位置,第一遍最大(最小)肯定会在最后了,

      然后第二次排序不计最后一个元素进行重排,然后以此类推

     public static void main(String[] args){
    
            int score[] = {3,5,8,3,5,6,9,7,4,1,5,98,7,6,12,7,45,56,5};
            for ( int i=0;i<score.length-1;i++) {
                for (int j=0;j<score.length-i-1;j++){
                    if(score[j]>score[j+1]){
                        int temp =score[j];
                        score[j]=score[j+1];
                        score[j+1]=temp;
                    }
                }
            }
    
            for ( int x: score) {
                System.out.println(x);
    
            }
    
        }
    

      2、选择排序

      关于选择排序,选择排序是怎样的,就是拿第一个,跟后面23456挨个去对比,如果第二个比第一个大,哎,记住第二个的下标,拿第二个跟第三个比去,以此类推,记住最大或最小的下标,然后跟第一个互换。每次第一个、第二个.....就是参与排序的里面总是最大或者最小的了

    public static void main(String[] args) {
            int[] score={3,5,8,3,5,6,9,7,4,1,5,98,7,6,12,7,45,56,5};
            for(int i = 0; i < score.length - 1; i++) {
                int step = i;
                for(int j = step + 1; j < score.length; j++){
                    if(score[j] > score[step]){
                        step = j;
                    }
                }
                if(i != step){
                    int temp = score[i];
                    score[i] = score[step];
                    score[step] = temp;
                }
            }
            for(int x:score){
                System.out.println(x);
            }
        }
    

      3、折半查找:

    public static void main(String[] args) {
    
            int[] nums = {1, 2, 3, 4, 5, 6, 7, 8,9};
            int step = mid(nums, 3);
            System.out.println(step);
        }
    
        public static int mid(int[] nums, int num) {
    
            int left = 0;
            int right = nums.length;
    
            while (left <= right) {
                int mid = (left + right) / 2;
                if (nums[mid] == num) {
                    return mid;
                } else if (num < nums[mid]) {
                    right = mid;
                } else if (num > nums[mid]) {
                    left = mid + 1;
                }
    
            }
            return -1;
        }
  • 相关阅读:
    前端开发网址
    Iconfot阿里妈妈-css高级应用
    手机端的META你知道多少?
    24个 HTML5 & CSS3 下拉菜单效果及制作教程
    css :clip rect 正确的使用方法
    layui :iframe 与 layer 的位置问题
    时间戳转现实时间的方法
    关于 iframe 的小问题若干
    使用 forever 启动 vue 需要注意的问题
    var 的一个坑,以及 let
  • 原文地址:https://www.cnblogs.com/lewskay/p/7803465.html
Copyright © 2011-2022 走看看