zoukankan      html  css  js  c++  java
  • 选择排序算法的JAVA实现

    1,采用选择排序对元素进行排列时,元素之间需要进行比较,因此需要实现Comparable<T>接口。即,<T extends Comparable<T>>. 更进一步,如果允许待比较的类型可以和它的父类型进行比较,则需要写成:<T extends Comparable<? super T>, 其中<? super T> 表示 T 的任意超类。

    2,SelectionSortArray.java 实现了选择排序的迭代形式和递归形式。具体代码如下:

    public class SelectionSortArray {
        /*
         * Task:将数组中前n个对象按升序排列
         * @param a Comparable 对象的数组
         * @param n 大于0的整数,表示数组的长度
         */
        public static <T extends Comparable<? super T>> void selectionSort(T[] a, int n){
            for(int index = 0; index < n-1; index++){
                int indexOfNextSmallest = getIndexOfSmallest(a, index, n-1);
                swap(a, index, indexOfNextSmallest);
            }
        }
        
        //返回索引first 至 索引last 之间的最小值的索引
        private static <T extends Comparable<? super T>> int getIndexOfSmallest(T[] a, int first, int last){
            T min = a[first];
            int indexOfMin = first;
            for(int index = first + 1; index <= last; index++){
                if(a[index].compareTo(min) < 0){
                    min = a[index];
                    indexOfMin = index;
                }//end if
            }
            return indexOfMin;
        }
        
        //交换数组元素不涉及compareTo方法,因而使用Object作为元素类型
        private static void swap(Object[] a, int i, int j){
            Object temp = a[i];//交换的并不是引用,而是具体的元素的值
            a[i] = a[j];
            a[j] = temp;
        }
        
        //选择排序的递归方法
        public static <T extends Comparable<? super T>> void selectionSort_Recursive(T[] a, int n){
            selectionSort(a, 0, n - 1);
        } 
        
        private static <T extends Comparable<? super T>> void selectionSort(T[] a, int first, int last){
            if(first < last)
            {
                int indexOfNextSmallest = getIndexOfSmallest(a, first, last);
                swap(a, first, indexOfNextSmallest);
                selectionSort(a, first + 1, last);
            }
        }
    }
  • 相关阅读:
    论JS函数传参时:值传递与引用传递的区别
    关于 rem
    致——自己
    用CSS3写的钟表
    HTML标签marquee实现滚动效果
    手机号截取
    CSS3绘制环形进度条
    限制内容长度(CSS,jQuery)
    移动web开发中遇到的一些问题收纳
    移动平台中 meta 标签的使用
  • 原文地址:https://www.cnblogs.com/hapjin/p/4471612.html
Copyright © 2011-2022 走看看