排序算法(三)选择排序

来源:互联网 发布:snmp简单网络管理协议 编辑:程序博客网 时间:2024/06/05 11:27

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

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,是不稳定的排序。

0 0