冒泡排序 java

GitHub - JourWon/sort-algorithm: 史上最全经典排序算法总结(Java实现)

package com.company;

import java.util.*;
import java.util.Arrays;

public class maopao {

    /**
     * Description:冒泡排序,从小到大排序或者从大到小排序
     *
     * @param shuzu 需要排序的数组
     * @author JourWon
     * @date 2019/7/11 9:54
     * @return
     */
    public static int[] bubbleSort(int[] shuzu) {


        int length = shuzu.length;

        // 外层循环控制比较轮数i
        for (int i = 0; i < length; i++) {
            // 内层循环控制每一轮比较次数,每进行一轮排序都会找出一个较大值
            // (array.length - 1)防止索引越界,(array.length - 1 - i)减少比较次数
            for (int j = 0; j < length - 1-i; j++) {
                // 前面的数大于后面的数就进行交换.从小到大用“>”,从大到小用“<”
                if (shuzu[j] > shuzu[j + 1]) {
                    // 把后面的小数据临时放在变量temp里面
                    int temp = shuzu[j + 1];
                    // 把前面这个大的数据赋值给后面的那个数
                    shuzu[j + 1] = shuzu[j];
                    // 把刚刚临时放在变量temp里面的较小的数据给前面这个数
                    shuzu[j] = temp;


                }
                // 经过在在这个for循环里面,完成了shuzu里面的数据交换位置(达成排序要求)。最后再直接返回这个shuzu即可。
            }

        }

        return (shuzu);




    }
    public static void main(String[] args) {
        int[] array = {3, 44, 38, 5, 47, 15, 66, 26, 27, 2, 46, 4, 19, 50, 48};
        // 原数组
        System.out.println(Arrays.toString(array));


        //排序后的数组(直接打印,因为返回的是字符串)
        // System.out.println(bubbleSort(array));





//for循环打印数组
        for(int i=0; i<maopao.bubbleSort(array).length; i++){
            System.out.print("----"+maopao.bubbleSort(array)[i]+"----");

        }



    }
}

 

posted @ 2022-08-03 14:34  很多无尾熊  阅读(27)  评论(0)    收藏  举报
本站已运行[ ]
正在加载今日诗词....