Algorithm - Selection Sort(Java)

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

package chimomo.learning.java.algorithm.sort;

import java.util.Arrays;

/**
 * @author Chimomo
 *
 * <p>
 * Basic Thought:
 *
 * The Selection Sort is following:
 * Each round of sorting selecting the smallest or biggest element
 * from the to-be-sorted sequence,
 * put it at the end of already-ordered sequence,
 * until all the elements of to-be-sorted sequence are sorted.
 * </p>
 *
 * <p>
 * Stability:
 *
 * Selection sort is not stable.
 * </p>
 */
public class SelectionSort {

    /**
     * Selection Sort
     *
     * @param a The array to be sorted
     */
    private static void selectionSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {

            // Store the subscript of the smallest element
            int min = i;

            // Find the smallest element
            for (int j = i + 1; j < a.length; j++) {
                if (a[j] < a[min]) {
                    min = j;
                }
            }

            // Put the smallest element into already-ordered sequence
            int t = a[min];
            a[min] = a[i];
            a[i] = t;

            // Print each round of sorting
            System.out.println(Arrays.toString(a));
        }
    }

    /**
     * Test program
     *
     * @param args The arguments
     */
    public static void main(String[] args) {
        int[] arr = {11, 16, 22, -3, 99, 0, 16, 6, -1, 99};

        System.out.println("Before selection sort:");
        System.out.println(Arrays.toString(arr));

        System.out.println("In selection sort:");
        SelectionSort.selectionSort(arr);

        System.out.println("After selection sort:");
        System.out.println(Arrays.toString(arr));
    }

}

/* ------ Running Results ------
Before selection sort:
[11, 16, 22, -3, 99, 0, 16, 6, -1, 99]
In selection sort:
[-3, 16, 22, 11, 99, 0, 16, 6, -1, 99]
[-3, -1, 22, 11, 99, 0, 16, 6, 16, 99]
[-3, -1, 0, 11, 99, 22, 16, 6, 16, 99]
[-3, -1, 0, 6, 99, 22, 16, 11, 16, 99]
[-3, -1, 0, 6, 11, 22, 16, 99, 16, 99]
[-3, -1, 0, 6, 11, 16, 22, 99, 16, 99]
[-3, -1, 0, 6, 11, 16, 16, 99, 22, 99]
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]
After selection sort:
[-3, -1, 0, 6, 11, 16, 16, 22, 99, 99]

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值