本文介绍: 核心:不断地选择剩余元素中的最小者。

选择排序

核心:不断地选择剩余元素中的最小者。

  1. 找到数组最小元素并将其和数组第一个元素交换位置
  2. 在剩下的元素中找到最小元素并将其与数组第二个元素交换,直至整个数组排序。

性质:

在这里插入图片描述

public class SelectioSort {
    public static void main(String[] args) {
        int unsortedArray[] = new int[]{8, 5, 2, 6, 9, 3, 1, 4, 0, 7};
        selectionSort(unsortedArray);
        System.out.println("After sort: ");
        for (int item : unsortedArray) {
            System.out.print(item + " ");
        }
    }

    public static void selectionSort(int[] array) {
        int len = array.length;
        for (int i = 0; i < len; i++) {
            for (int item : array) {
                System.out.print(item + " ");
            }
            System.out.println();
            int min_index = i;
            // 将最小值下标找出
            for (int j = i + 1; j < len; j++) {
                if (array[j] < array[min_index]) {
                    min_index = j;
                }
            }
            int temp = array[min_index];
            array[min_index] = array[i];
            array[i] = temp;
        }
    }
}

输出

8 5 2 6 9 3 1 4 0 7 
0 5 2 6 9 3 1 4 8 7 
0 1 2 6 9 3 5 4 8 7 
0 1 2 6 9 3 5 4 8 7 
0 1 2 3 9 6 5 4 8 7 
0 1 2 3 4 6 5 9 8 7 
0 1 2 3 4 5 6 9 8 7 
0 1 2 3 4 5 6 9 8 7 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 
After sort: 
0 1 2 3 4 5 6 7 8 9 

原文地址:https://blog.csdn.net/JustDI0209/article/details/134810088

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_45820.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注