排序—选择排序

本文借鉴与 一线码农 的博客。

第一步: 我们拿80作为参照物(base),在80后面找到一个最小数20,然后将80跟20交换。                      

第二步:  第一位数已经是最小数字了,然后我们推进一步在30后面找一位最小数,发现自己最小,不用交换。

第三步:........

最后我们排序完毕。大功告成。

 

package com.ufida.practice.suanfa.sort;

public class SelectionSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr= new int[]{7,22,11,5,400,99,20,22,5};
        new SelectionSort().SelectionSort(arr);
        for(int i : arr)
            System.out.println(i);

    }

    public void swap(int arr[],int a,int b){    
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] =temp;
    }
    
    public void SelectionSort(int[] targetArr){
        for(int i = 0;i<targetArr.length;i++){
            int temp = i;
            for(int j = i+1;j<targetArr.length;j++){            
                if(targetArr[j]<targetArr[temp])
                    temp = j;                                        
            }
            swap(targetArr,i,temp);                
        }
    }
}

 

因为年轻,所有没有失败。
原文地址:https://www.cnblogs.com/wangchy0927/p/2845788.html