【数据结构】实现冒泡排序算法(Java语言)

冒泡排序

  • 编程实现冒泡排序函数。public static void bubbleSort(int arr[])。其中arr存放待排序的数据,数组长度不大于1000
  • 函数接口定义:

/* 对长度为n的数组arr执行冒泡排序 */

public static void bubbleSort(int arr[]);

请实现bubbleSort函数,使排序后的数据从小到大排列。

c 复制代码
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int [n];
        for(int i = 0; i < n; i ++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();
        bubbleSort(arr);
        print(arr);         
    }
    public static void print(int[] arr) {
        for (int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println("");
    }

	// ---------------------------------------------------------------------------
    // 【实现代码如下】
    // 排序函数
	public static void bubbleSort(int arr[]) {
	    // 获取数组的长度
	    int n = arr.length;
	    // 外层循环控制排序需要进行的轮数,每完成一轮,最大的元素会被放到正确的位置
	    for (int i = 0; i < n - 1; i++) {
	        // 内层循环控制每轮需要进行比较的次数,随着排序的进行,比较次数逐渐减少
	        for (int j = 0; j < n - i - 1; j++) {
	            // 比较相邻两个元素,如果前面的元素大于后面的元素,则交换它们的位置
	            if (arr[j] > arr[j + 1]) {
	                // 进行元素交换
	                int temp = arr[j];
	                arr[j] = arr[j + 1];
	                arr[j + 1] = temp;
	            }
	        }
	    }
	}
}
相关推荐
数据分析螺丝钉17 分钟前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games17 分钟前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
五味香17 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
无理 Java22 分钟前
【技术详解】SpringMVC框架全面解析:从入门到精通(SpringMVC)
java·后端·spring·面试·mvc·框架·springmvc
PYSpring39 分钟前
数据结构-LRU缓存(C语言实现)
c语言·数据结构·缓存
毕小宝41 分钟前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡1 小时前
DenseNet算法:口腔癌识别
算法
希望有朝一日能如愿以偿1 小时前
算法(食物链)
算法
gobeyye1 小时前
spring loC&DI 详解
java·spring·rpc
鱼跃鹰飞1 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试