Data Structure-Selection Sorting Method

  There are two ways to choose the sorting method. One is that in all data, when sorting from large to small, the maximum value is placed in the first position; if sorting from small to large, the maximum value is placed End of position.

  For example, when N data needs to be sorted from small to large, first compare the data at the first position with the data at 2, 3, 4 ... N positions. If the data is less than or equal to one of the locations, the data at the two locations will not change; if it is greater than one of the locations, the data at the two locations will be swapped. After the new data of the first position after the exchange, continue to find the next position data for comparison, until the end of the position, at this time the data of the first position is the minimum value of the sort sequence. Next, select the second position data, and compare the data at 3, 4, 5, ... N positions in sequence, and put the minimum value of the remaining sort into the second position. Follow this method until the minimum of (N-1) positions is found, then complete the sorting of the selection sorting method from small to large.

Calculus process

 

Selection analysis

  1. Whether it is the worst case, the best case or the average case, you need to find the minimum (maximum), so the number of comparisons is (n-1) + (n-2) + (n-3) + ... + 3 + 2 + 1 = n (n-1) / 2 times; the time complexity is O (n ^ 2).
  2. Since the selection sorting is to directly exchange the minimum or maximum value with the key value that is not sorted at the front, the data sorting order is likely to be changed, so it is not a stable sorting method.
  3. Only one extra space is needed, so the space complexity is optimal.
  4. This sorting method is suitable for cases where the amount of data is small or some data has been sorted.

example1

/ ** 
 * Selection method sorting 
 * 
 * / 
public  class SelectionSort { 

    public  static  void main (String [] args) {
         int data [] = new  int [] {9, 7, 5, 3, 4, 6 }; 
        System. out.print ( "raw data:" ); 
        showData (data); 
        select (data); 
        System.out.print ( "sorted data:" ); 
        showData (data); 
    } 
    
    private  static  void select ( int data [ ]) {
         int i, j, tmp;
         for (i = 0; i < data.length - 1; i++) {
            for (j = i + 1; j < data.length; j++) {
                if (data[i] > data[j]) {
                    tmp = data[i];
                    data[i] = data[j];
                    data[j] = tmp;
                }
            }
            showData(data);
        }
    }
    
    private static void showData(int data[]) {
        for (int i = 0; i < data.length; i++) {
            System.out.printf("[%d]", data[i]);
        }
        System.out.printf("%n");
    }

}

 

Guess you like

Origin www.cnblogs.com/qpliang/p/12686875.html