大家好,又见面了,我是你们的朋友全栈君。
public class BubbleSoft { public static void main(String[] args) { //使用冒泡排序对一组数进行排序,使得最终结果是一个从小到大的顺序 int[] arr = {11, 23, 45, 22, 1, 45, 25, 68, 19}; System.out.println("排序之前:"); printArray(arr); System.out.println(); //定义一个方法实现对数组的冒泡排序 int[] arr1 = bubbleSoft(arr); System.out.println("排序之后:"); printArray(arr1); } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i == arr.length - 1) { System.out.print(arr[i] + "]"); } else if (i == 0) { System.out.print("[" + arr[i] + ","); } else { System.out.print(arr[i] + ","); } } } //定义方法实现冒泡排序 /** * 返回值类型:int[] * 参数列表:int[] arr */ public static int[] bubbleSoft(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { // 外层控制排序的次数 for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/147927.html原文链接:https://javaforall.net