您的位置:首页 > 博客中心 > 编程语言 >

打印三角形和冒泡排序

时间:2022-03-29 01:44

打印三角形

public class TriangleDemo {
    public static void main(String[] args) {
        for (int j = 1; j <= 5; j++) {
            for (int i = 5; i >= j; i--) {
                System.out.print(" ");
            }
            for (int i = 1; i <= j; i++) {
                System.out.print("*");
            }
            for (int i = 1; i < j; i++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

运行效果:
技术图片

思路:

依次打印1、2、3部分就行
技术图片

冒泡排序

  1. 符合要求时相邻元素互换位置
  2. 每一轮循环都会把最大/最小的元素排到最尾部
import java.util.Arrays;

public class Demo1 {
    public static void main(String[] args) {
        int[] arr = {1, 4, 5, 2, 3};
        
        int[] result = bubbleSort(arr);
        System.out.println(Arrays.toString(result));
    }

    public static int[] bubbleSort(int[] a) {
        int temp = 0;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
        return a;
    }
}

运行结果:
技术图片

本类排行

今日推荐

热门手游