zoukankan      html  css  js  c++  java
  • java学习之数组排序一:选择排序

    在讲完java中数组定义的两种方式之外,这里需要讲一下对数组常用的方法,第一个就是排序。

    加入我们现在有个数组:int[] arr = {12,87,34,3,98,33,103};

    思路1:

      1、首先拿数组当中的第一个数字与其他数字一一做比较,如果比第一个数字大,那么就两个元素调换下位置,如果小于或者等于就维持原来的状态。循环往复,直至确定第一个数字是这个数组当中的最小值。然后把索引为0的元素,放到一边,之后再用索引为1的元素与其他元素依次比较,如果大于索引1的位置的元素,那么两者互换下位置,如果小于或者等于那么则保持各自位置不变,之后在索引位置2的位置,确定剩下的数字当中是最小的,其他位置的元素也是按照这种排序方法。需要注意的是最后一个元素就不用比较了,肯定是最大的。

    选择排序:

    class SelectSort
    {
    	
    	public static void main(String[] args) 
    	{
    		
    		int[] arr = {12,87,34,39,134,4,45,8,21233,99};
    
    		printArr(arr);
    
    		selectSort(arr);
    
    		printArr(arr);
    
    	}
    
    	public static void selectSort(int[]  arr){
    
    		for(int i = 0; i<arr.length-1; i++)
    		{
    
    			for(int a = i + 1; a<=arr.length-1 ; a++)
    			{
    			/**
    			*	if(arr[i]>arr[a])
    			*	{
    			*		int temp = arr[i];
    			*		arr[i] = arr[a];
    			*		arr[a] = temp;
    			*	}
    			*/
    				if(arr[i]>arr[a])
    					swap(arr,i,a);
    
    			}
    
    		}
    
    	}
    
    	public static void printArr(int[] arr)
    	{
    		System.out.print("[");
    		for(int i=0 ; i<arr.length ; i++){
    
    			System.out.print(arr[i]);
    			if(i<arr.length-1)
    				System.out.print(",");
    
    		}
    		System.out.print("]");
    		System.out.println();
    
    	}
    
    	public static void swap(int[]arr,int x, int y)
    	{
    
    		int temp;
    		if(arr[x]>arr[y])
    		{
    
    			temp = arr[x];
    			arr[x] = arr[y];
    			arr[y] = temp;
    
    		}
    
    	}
    
    }
    

      

  • 相关阅读:
    [leetcode]Remove Nth Node From End of List @ Python
    [leetcode]Swap Nodes in Pairs @ Python
    [leetcode]Linked List Cycle II @ Python
    [leetcode]Linked List Cycle @ Python
    [leetcode]LRU Cache @ Python
    [leetcode]Reorder List @ Python
    [leetcode]Insertion Sort List @ Python
    [leetcode]Sort List @ Python
    [leetcode]3Sum Closest @ Python
    [elk]elasticsearch实现冷热数据分离
  • 原文地址:https://www.cnblogs.com/sunchuanzhen/p/3323646.html
Copyright © 2011-2022 走看看