zoukankan      html  css  js  c++  java
  • 选择排序

    选择排序

    思路

    1.一开始的时候,整个数组是无序的,我们遍历数组找到最小的值,将这个最小的值放到它应该放的位置也就是a[0]
    2.接着我们再从a[1]到a[n]中继续遍历找到最小的值,并将它放到正确的地方a[1]
    3.这样a[0],a[1]就是有序的了
    4.我们在循环这样的过程从a[i]-a[n]中找到最小的值,放到a[i]位置,使得前i个元素有序
    5.直到整个数组是有序的

    代码

    package sort;
    
    public class SelectSort {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		int[] arr= {7,6,5,4,3,2,1};
    		SelectSort(arr);
    		for(int i=0;i<arr.length;i++) {
    			System.out.printf("%d ",arr[i]);
    		}
    		System.out.println();
    	}
    	
    	public static void SelectSort(int[] a) {
    		int minIndex=0;//最小值的下标
    		int min=0;//最小值
    		int len=a.length;//获取a的长度
    		for(int i=0;i<len-1;i++) {
    			min=a[i];//假设a[i]为[i,len)的中的最小值
    			minIndex=i;//最小下标为i
    			for(int j=i+1;j<len;j++) {
    				if(a[j]<a[minIndex]) {//在[i,len)中寻找最小值
    					minIndex=j;//如果有比假设最小值更加小的值就刷新下标和值
    					min=a[j];
    				}
    				int temp=a[i];//将找到的最小值放到对应正确的位置
    				a[i]=a[minIndex];
    				a[minIndex]=temp;
    			}
    		}
    	}
    
    }
    
  • 相关阅读:
    HDU 5059 Help him
    HDU 5058 So easy
    HDU 5056 Boring count
    HDU 5055 Bob and math problem
    HDU 5054 Alice and Bob
    HDU 5019 Revenge of GCD
    HDU 5018 Revenge of Fibonacci
    HDU 1556 Color the ball
    CodeForces 702D Road to Post Office
    CodeForces 702C Cellular Network
  • 原文地址:https://www.cnblogs.com/mengxiaoleng/p/11663812.html
Copyright © 2011-2022 走看看