2021排序算法

自定义的工具类

实现了随机产生数组,打印数组的功能

package com.mao.sort;

import java.util.Random;

/**
 * author 小毛桑
 *
 * @date 2021/10/18 0018 12:26
 */
public class Common {

    public int[] setNumber(){
        Random random = new Random();
        int count = 0;
        while (count == 0){
            count = random.nextInt(22);
        }
        int[] arr = new int[count];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(100);
        }
        return arr;
    }

    public void printArray(int[] array){
        for (int i = 0; i < array.length; i++) {
            System.out.printf(" [" + array[i] +"] ");
        }
    }
}

排序

冒泡排序

// 冒泡排序
    public int[] bubbleSort(int[] array){
        int temp = 0;// 临时变量
        // 第一次循环遍历之下进行第二次遍历,比较相邻的元素。如果第一个比第二个大,就交换他们两个。一次 i 下,会找到没有排好序的最大的那个元素,将它的位置排好。 
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j+1]){
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
        return array;
    }

选择排序

    // 选择排序
    public int[] choiceSort(int[] array){
        for (int i = 0; i < array.length -1; i++) {
            int min = i,temp;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[min]){
                    min = j;
                }
            }
            if (i != min){
                temp = array[i];
                array[i] = array[min];
                array[min] = temp;
            }
        }
        return array;
    }

快速排序

    // 快速排序
    public int[] quicklySort(int[] array, int low, int high){

        int i, j, temp, t;

        if(low>high){
            return null;
        }

        i = low;
        j = high;
        temp = array[low]; // temp 为基准

        while (i<j) {
            while (temp<=array[j]&&i<j) {//先看右边,依次往左递减
                j--;
            }
            while (temp>=array[i]&&i<j) {//再看左边,依次往右递增
                i++;
            }
            if (i<j) {
                t = array[j];
                array[j] = array[i];
                array[i] = t;
            }
        }
        //最后将基准为与i和j相等位置的数字交换
        array[low] = array[i];
        array[i] = temp;
        quicklySort(array, low, j-1);//递归调用左半数组
        quicklySort(array, j+1, high);//递归调用右半数组

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值