用Java实现常见的排序算法

一、冒泡排序

public class Pubble {

    public static void main(String[] args) {
        int []numbers = {2,5,28,90,45,23,68};
        Pubble.PubbleSort(numbers);
        for (int number : numbers) {
            System.out.println(number);
        }
    }

    public static void PubbleSort(int nums[]){
        int temp = 0;
        int size = nums.length;
        for (int i = 0; i < size - 1; i++){
            for (int j = 0; j < size - 1 - i; j++){
                if(nums[j] > nums[j+1]){
                    temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
    }
}

二、选择排序

public class Select {
    
    public static void main(String[] args) {
        int array[] = {3,8,4,6,7,12,23};
        Select.SelectSort(array);
        for (int i : array) {
            System.out.println(i);
        }
    }

    public static void SelectSort(int nums[]){
        int size = nums.length;
        int temp = 0;
        for(int i = 0; i < size; i++){
            int min = i;
            for (int j = i; j < size; j++){
                if(nums[j] < nums[min]){
                    min = j;
                }
                temp = nums[min];
                nums[min] = nums[i];
                nums[i] = temp;
            }
        }
    }
}

三、插入排序

public class Insert {

    public static void main(String[] args) {
        int[] array = {3,7,2,4,1,9,6};
        Insert.InsertSort(array);
        for (int i : array) {
            System.out.println(i);
        }
    }

    public static void InsertSort(int[] array){
        int temp = 0;
        int size = array.length;
        for (int i = 1; i < size; i++){
            for (int j = i - 1; j >= 0 && array[j] > array[j+1];j--){
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
}

四、二分法

public class Binary {

    public static void main(String[] args) {
        int[] array = {3,5,7,3,6,5,3,6,8,9};
        System.out.println(Binary.BinarySearch(array,9));
    }

    public static int BinarySearch(int array[],int findValue){
        int start = 0;
        int end = array.length-1;

        while (start <= end){
            int middle = start + (end - start)/2;
            int middleValue = array[middle];
            if(findValue == middleValue){
                return middle;
            }else if(findValue < middleValue){
                end = middle -1;
            }else {
                start = middle + 1;
            }
        }
        return -1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值