java实现数组的冒泡排序、选择排序代码

本文介绍了两种基本的数组排序算法——冒泡排序和选择排序,并通过Java代码实现了这两种算法。冒泡排序通过相邻元素的比较逐步将较大元素移至数组末端;而选择排序则通过寻找最小元素并将其置于正确位置来实现排序。

数组排序之冒泡排序: 
相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处

package cn.lgt.sortarray;

public class MaoPaoSort {
    public static void maoPaoSort(int[] arr){
        //冒泡排序
        for(int i = 0; i < arr.length; i++){
            for(int j = 0; j < arr.length-1-i; j++){
                if(arr[j] > arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
            //PrintArray.printArray(arr);
        }
        PrintArray.printArray(arr);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

数组排序之选择排序: 
从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在了最小索引处

package cn.lgt.sortarray;

public class XuanZeSort {
    //选择排序
    public static void xuanZeSort(int[] arr){
        for(int i = 0; i < arr.length; i++){
            for(int j = i+1; j< arr.length; j++){
                if(arr[i] > arr[j]){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
            //PrintArray.printArray(arr);
        }
        PrintArray.printArray(arr);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

数组遍历输出

package cn.lgt.sortarray;

public class PrintArray {
    public static void printArray(int[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i != arr.length - 1) {
                System.out.print(arr[i] + ", ");
            } else {
                System.out.print(arr[i]);
            }
        }
        System.out.println("]");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

main方法代码

package cn.lgt.sortarray;

public class SortDemo {
    public static void main(String[] args) {
        System.out.println("排序算法");
        System.out.println("-----------------------");
        int[] array = {23, 2, 12, 33, 65, 46, 9, 1, 5};
        PrintArray.printArray(array);//输出数组
        //MaoPaoSort.maoPaoSort(array);//冒泡排序
        XuanZeSort.xuanZeSort(array);//选择排序
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值