sf02_选择排序算法Java Python rust 实现

Java 实现

package common;

public class SimpleArithmetic {
    
    /**
     * 选择排序
     * 输入整形数组:a[n] 【4、5、3、7】
     * 1. 取数组编号为i(i属于[0 , n-2])的数组值 a[i],即第一重循环
     * 2. 假定a[i]为数组a[k](k属于[i,n-1])中的最小值a[min],即执行初始化 min =i 
     * 3. 取数组编号为m(m属于[i+1,n-1])的数组值 a[m],即第二重循环
     * 4. 若 a[m] < a[min], 则 min = m ; min 始终记录 a[k]中的最小值
     * 5. 当 min != i时,即第二步的假定a[i]为a[k]中的最小值不成立时,需要将a[min]与a[i]的值互换 
     * 
     * @param arr 整形数组
     */
    public static void selectSort(int[] arr){
        int n = arr.length;
        int min = 0;
        int tmp = 0;
        for(int i = 0; i < n-1; i++){
            min = i;
            for(int m = i + 1; m < n; m++){
                if(arr[m]<arr[min]) min =m;
            }
            if(i != min){
                tmp = arr[i];
                arr[i] = arr[min];
                arr[min] = tmp;
            }//end of if
        }//end of for 
        
    }

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        int[] arr = {12,23,9,24,15,3,18};
        SimpleArithmetic.selectSort(arr);
        
        
        for(int i = 0; i < arr.length; i++){
            System.out.print(arr[i]+" ");
        }
        //输出 3 9 12 15 18 23 24  

    }

}

 

Python 实现

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class SimpleArithmetic:
    def selectSort(self,arr):
        v_len = len(arr)
        v_index_i = 0
        while v_index_i != v_len -1:
            i = arr[v_index_i]
            v_min = i
            for m in arr[v_index_i+1:v_len]:
                if m < v_min:
                    v_min = m
            if i != v_min:
                v_tmp = arr.index(v_min)
                arr[v_index_i] = v_min
                arr[v_tmp] = i
            v_index_i = v_index_i + 1

>>> sa = SimpleArithmetic()
>>> arr = [12,23,9,24,15,3,18]
>>> sa.selectSort(arr)
>>> arr
[3, 9, 12, 15, 18, 23, 24]
>>> 

 

rust实现

pub fn select_sort_vec(v1: &mut Vec<i32>){
    let le = v1.len();

    let mut tmp_min_index = 0;

    for i in 0..(le-1) {
        if let Some(elem) = v1.get(i){
            tmp_min_index = i;

            for m in (i+1)..le {
                if let Some(e) = v1.get(m) {
                    if let Some(emin) = v1.get(tmp_min_index){
                        if *e < *emin{
                        tmp_min_index = m;
                        }
                    };
                }
            }

            if i != tmp_min_index {
                v1.swap(i,tmp_min_index);
             }
        }
    }
}


pub fn select_sort_vec_test() {
    let mut v1 = vec![1, 3, 2,5,11,4,9];
    select_sort_vec(&mut v1);

    for (i,val) in v1.iter().enumerate() {
        println!("last {}:{}",i,val);
    }
}

 

posted @ 2015-10-21 17:01  方诚  阅读(238)  评论(0编辑  收藏  举报