选择排序 -java代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package sort;
 
/**
 * @author: tianhaichao
 * @date: 2022/9/17 20:20
 * @description:选择排序,时间复杂度 O(n * n)
 * 双重for循环
 * 假定一个最大值是array[i],内层循环,每次循环都用arrayv[j]与max比大小,如果,大于就用j替换i做最大值,进入下层循环比较,就像打擂台似的,循环结束选出最大的。
 * 外层循环,每循环一次,交换最大值和i位置上的值,排好一个数,放在i的位置,下次循环从i+1开始
 * <p>
 * 简单来说就是打擂台,每次选出一个最大的,排好一个数
 */
public class SelectSort {
    public static void sort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int temp;
            int maxIndex = i;
            for (int j = i; j < array.length; j++) {
                if (array[j] > array[maxIndex]) {
                    maxIndex = j;
                }
            }
            if (maxIndex != i) {
                temp = array[i];
                array[i] = array[maxIndex];
                array[maxIndex] = temp;
            }
            print(array);
        }
    }
 
    public static void main(String[] args) {
        int[] array = new int[]{1, 2, 3, 6, 10, 9, 5, 4};
        SelectSort.sort(array);
        System.out.println("======================");
    }
 
    public static void print(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print("   ");
            System.out.print(array[i]);
            System.out.print("   ");
        }
        System.out.println();
    }
}

  

posted @   田海超  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示