java Bubble sort

1 图形

2 java 冒泡排序

        int[] arr = {5, 4, 3, 2, 1};
        for(int i =0;i<arr.length-1;i++) {//arr.length = 5, i <= 3
            for (int j = 0; j < arr.length-i-1; j++) { // j <= 3
                if (arr[j] > arr[j + 1]) {// 和+1 元素比较,大于互换
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        for (int temp : arr){
            System.out.print(temp + " ");
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. Here is the Java code for Bubble Sort: ``` public class BubbleSort { public static void main(String[] args) { int[] arr = {5, 2, 7, 3, 1}; bubbleSort(arr); for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); } } public static void bubbleSort(int[] arr){ int n = arr.length; int temp = 0; for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(arr[j-1] > arr[j]){ temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } } ``` In this code, we have an array of integers that we want to sort using Bubble Sort. We define a method called `bubbleSort` that takes an array as input and sorts it using the Bubble Sort algorithm. The outer loop iterates through the array from the first element to the last element. The inner loop iterates through the array from the second element to the last element. Inside the inner loop, we compare the current element with the previous element. If the current element is smaller than the previous element, we swap them. After the inner loop completes, the largest element is at the end of the array. We repeat this process until the entire array is sorted. Finally, we print the sorted array using a for loop.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值