zoukankan      html  css  js  c++  java
  • 简单排序

    一冒泡排序

    二选择排序

    三插入排序

    下面我们分步讲一下这三种排序。首先来看一下冒泡排序。

    package ch02;
    
    public class BubbleSort {
    
        public static void sort(long [] arr){
            long temp = 0;
            for (int i = 0;i<arr.length-1;i++) {//i表示第几趟排序
                for (int j = arr.length-1;j>i;j--) {
                    if (arr[j] <arr[j-1]) {
                        //交换
                        temp = arr[j];
                        arr[j] = arr[j-1];
                        arr[j-1] = temp;
                    }
                }
            }
        }
        
        public static void main(String[] args) {
            long[]arr = new long[5];
            arr[0] = 34;
            arr[1] = 23;
            arr[2] = 1;
            arr[3] = 2;
            sort(arr);
            for (int i = 0;i<arr.length;i++) {
                System.out.print(arr[i]+" ");
            }
            
        }
        
    }

    2:选择排序:代码实现

    package ch02;
    
    public class SelectionSort {
    
        public static void sort(long [] arr){
            int k = 0;
            long temp = 0;
            for (int i = 0;i<arr.length;i++) {//趟数
                k = i;
                for (int j = i;j<arr.length;j++) {
                    if (arr[j] < arr[k]) {//选择最小的交换
                        k = j;
                    }
                }
    //交换 temp
    = arr[i]; arr[i] = arr[k]; arr[k] = temp; } } public static void main(String[] args) { long[]arr = new long[5]; arr[0] = 34; arr[1] = 23; arr[2] = 1; arr[3] = 2; sort(arr); for (int i = 0;i<arr.length;i++) { System.out.print(arr[i]+" "); } } }

    3,插入排序:代码实现(代码有问题)

    package ch02;
    
    public class InsertSort {
    
        public static void sort(long [] arr){
            long temp = 0;
            for (int i = 1;i<arr.length;i++) {
                temp = arr[i];
                int j = i;
                while (j > 0 && arr[j] >= temp) {
                    arr[j] = arr[j-1];
                    j--;
                }
                arr[j] = temp;
            }
        }
        public static void main(String[] args) {
            long[]arr = new long[5];
            arr[0] = 34;
            arr[1] = 23;
            arr[2] = 1;
            arr[3] = 2;
            arr[4] = 0;
            sort(arr);
            for (int i = 0;i<arr.length;i++) {
                System.out.print(arr[i]+" ");
            }
        }
    }
  • 相关阅读:
    clipboard复制剪贴板功能,以及用sea.js时报错---Uncaught ReferenceError: Clipboard is not defined
    关于字体跨域
    关于 sass
    移动端返回上一页
    第二次结对编程作业
    第一次结对编程作业
    第一次个人编程作业
    软工实践第一次作业
    XGB算法梳理
    GBDT算法梳理
  • 原文地址:https://www.cnblogs.com/airycode/p/5310460.html
Copyright © 2011-2022 走看看