java排序算法之选择排序

1、循环找到第n个最小值,放在第n个位置

package com.sor;

import java.util.Random;

public class TestSelectSort {
	//[3, 25, 20, 79, 18, 58, 20, 38, 66, 56]
	public static int[] selectSort(int[] r){
		int index = 0;
		for (int i = 0; i < r.length; i++) {
			int min=r[i];
			for (int j = i; j<r.length; j++) {
				if (r[j]<min) {
					min=r[j];
					index=j;
				}
			}
			//每轮最小值
			swap(r,i,index);
		}
	
		return r;
	}
	private static void swap(int[] number, int i, int j) {
		int t;
		t = number[i];
		number[i] = number[j];
		number[j] = t;
	}
	public static void display(int[] R){  
        System.out.println();  
        for(int i=0;i<R.length;i++){  
            System.out.print(R[i]+" ");  
        }  
    }  

	
	public static void main(String[] args) {
	      final int M = 10;//定义数组大小为50   
	        int []R = new int[M];  
	        for(int i=0;i<M;i++){  
	            R[i] = new Random().nextInt(100);//生成100以内的随机数   
	        }  
	        display(R);  
	        R = selectSort(R);  
	        display(R); 
	}
}


 

你可能感兴趣的:(java排序算法之选择排序)