欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java选择排序、冒泡排序和插入排序

程序员文章站 2022-05-09 11:07:00
package com.sort;import java.util.Arrays;public class Test01 { public static void main(String[] args) { System.out.println("选择排序:"); selectSort(); System.out.println("冒泡排序:"); bubbleSort(); System.out.prin....
package com.sort;

import java.util.Arrays;

public class Test01 {
    public static void main(String[] args) {
        System.out.println("选择排序:");
        selectSort();

        System.out.println("冒泡排序:");
        bubbleSort();

        System.out.println("插入排序:");
        insertSort();

    }

    //选择排序
    private static void selectSort(){
        int[] str = {4, 2, 6, 10, 7};
        int strlen = str.length;
        for (int i = 0; i < strlen - 1; i++) {
            for (int j = i + 1; j < strlen; j++) {
                if (str[i] > str[j]) {
                    int temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
            System.out.print("第" + (i+1) + "次的排序结果为:" + Arrays.toString(str) + "\n");
        }
    }

    //冒泡排序
    private static void bubbleSort(){
        int[] str = {4, 2, 6, 10, 7};
        boolean bool;
        int strlen = str.length;
        for (int i = 0; i < strlen - 1; i++) {
            bool = true;
            for (int j = 0; j < strlen - i - 1; j++) {
                if (str[j] > str[j+1]) {
                    int temp = str[j];
                    str[j] = str[j+1];
                    str[j+1] = temp;
                    bool = false;
                }
            }
            System.out.print("第" + (i+1) + "次的排序结果为:" + Arrays.toString(str) + "\n");
            if (bool) {
                break;
            }
        }
    }

    //插入排序
    private static void insertSort(){
        int[] str = {4, 2, 6, 10, 7};
        int j;
        int strlen = str.length;
        for (int i = 1; i < strlen; i++) {
            int temp = str[i];
            for (j = i; j > 0 && (temp - str[j-1]) < 0; j--) {
                str[j] = str[j-1];
            }
            str[j] = temp;
            System.out.print("第" + i + "次的排序结果为:" + Arrays.toString(str) + "\n");
        }
    }

}

本文地址:https://blog.csdn.net/qq_42472710/article/details/109632698