simple selection sort

package cn.com;

import java.util.Arrays;

/** Simple selection sort
 * This example is arranged from small to large
 * @author Administrator
 *
 */
public class SimpleSelSort {
    public static void main(String[] args) {
        int[] array = {82,2,4,5,6,56,34,23,90,-1,100,91};
        doSort(array);
        System.out.println(Arrays.toString(array));
    }
    
    /** There is no need to select the maximum value at the beginning, you can first select the subscript of the maximum value, and then exchange the position with the disordered end element
     * Compared to bubbling, only the last operation after selecting the largest (smallest) element is a swap
     * @param array
      */ 
    private  static  void doSort( int [] array){
         for ( int i = array.length-1; i >0; i--) { // The last remaining element does not need to be arranged 
            int maxIndex = 0; // each time assume the first is the max value 
            for ( int j = 1; j <= i; j++) { // start from the second than 
                if (array[j]> array[maxIndex]) {
                    maxIndex = j;
                }
            }
            // Swap the largest element with the unordered end element 
            int temp = array[i]; // Keep the unordered segment end element 
            array[i] = array[maxIndex]; // Put the largest element into the end 
            array[maxIndex] ] = temp; // put the original end element into the original maximum element
            
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324937597&siteId=291194637