• 冒泡排序


    package demo;

    public class MaoPao {
    public static void main(String[] args) {
    //定义一个数组
    int [] arr = {1,6,3,9,4,2,5,8,0,7};
    System.out.println("排序前:" + arrayToString(arr));

    /*

    //第一次比较
    for (int i = 0; i < arr.length - 1 - 0; i++) {
    if (arr [i] > arr [i + 1]){
    int temp = arr [i];
    arr [i] = arr [i + 1];
    arr [i + 1] = temp;
    }
    }
    System.out.println("第一次比较后:" + arrayToString(arr));

    //第二次比较
    for (int i = 0; i < arr.length - 1 - 1; i++) {
    if (arr [i] > arr [i + 1]){
    int temp = arr [i];
    arr [i] = arr [i + 1];
    arr [i + 1] = temp;
    }
    }
    System.out.println("第二次比较后:" + arrayToString(arr));

    //第三次比较
    for (int i = 0; i < arr.length - 1 - 2; i++) {
    if (arr [i] > arr [i + 1]){
    int temp = arr [i];
    arr [i] = arr [i + 1];
    arr [i + 1] = temp;
    }
    }
    System.out.println("第三次比较后:" + arrayToString(arr));

    //第四次比较
    for (int i = 0; i < arr.length - 1 - 3; i++) {
    if (arr [i] > arr [i + 1]){
    int temp = arr [i];
    arr [i] = arr [i + 1];
    arr [i + 1] = temp;
    }
    }
    System.out.println("第四次比较后:" + arrayToString(arr));
    */

    for (int x = 0;x < arr.length - 1;x ++){
    for (int i = 0; i < arr.length - 1 - x; i++) {
    if (arr [i] > arr [i + 1]){
    int temp = arr [i];
    arr [i] = arr [i + 1];
    arr [i + 1] = temp;
    }
    }
    }
    System.out.println("排序后:" + arrayToString(arr));
    }

    public static String arrayToString(int [] arr){
    StringBuilder s = new StringBuilder();
    s.append("[");

    for (int i = 0; i < arr.length; i++) {
    if (i == arr.length - 1){
    s.append(arr [i]);
    }else {
    s.append(arr [i]).append(", ");
    }
    }
    s.append("]");
    String str = s.toString();
    return str;
    }
    }
  • 相关阅读:
    绑定class -vue
    二叉树按层打印,并且按层换行的方法
    curl相关知识
    python创建简单的http服务器
    有关rides数据库的想法
    java模拟实现有序表操作
    php静态方法
    php关闭浏览器不终止运行
    php读取图片以二进制输出
    借用face++人脸识别,来识别年龄
  • 原文地址:https://www.cnblogs.com/lixiang0622/p/13439333.html
Copyright © 2020-2023  润新知