排序算法(三)选择排序

选择排序是一种简单直观的排序算法。它的工作原理如下:首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元素,放到排序序列末尾。以此类推,直到所有的元素均排序完毕。

Java实现选择排序算法:

package com.review.sort;

public class SelectSort {

    public static void selectSort(int[] source) {
        for (int i = 0; i < source.length; i++) {
            for (int j = i + 1; j < source.length; j++) {
                if (source[i] > source[j]) {
                    swap(source, i, j);
                }
            }
        }

    }

    private static void swap(int[] source, int x, int y) {
        int temp = source[x];
        source[x] = source[y];
        source[y] = temp;
    }

    public static void main(String args[]) {
        int[] a = { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
        int i;
        selectSort(a);
        for (i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
}

算法分析:
选择排序的交换操作介于0和n-1次之间;选择排序的比较操作为n(n-1)/2次之间;选择排序的赋值操作介于0和3(n-1)次之间;其最差、平均时间复杂度都为O(n^2)。
空间复杂度为1,是不稳定的排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值