"Algorithm" Note 3 - Select sort, insertion sort, Shell sort

  • Sort common code
  • Selection Sort
  • Insertion Sort
  • Shell sort

Sort common code

Common code to support any data type implemented Comparable interface sorting, sorting algorithms differences embodied in the implement of the sort method.

public class Selection {
    public static void sort(Comparable[] a) {
        //待实现
    }

    private static boolean less(Comparable a, Comparable b) {
        return a.compareTo(b) < 0;
    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    private static boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++) {
            if (less(a[i], a[i - 1])) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] input = StdIn.readAllInts();
        Integer[] a1 = new Integer[input.length];
        for (int i = 0; i < input.length; i++) {
            a1[i] = input[i];
        }
        sort(a1);
        assert isSorted(a1);
    }
}

Selection Sort

Select the sorting process is: to find the smallest element in the array, and then it will be the first element in the array exchange position, if the first element is the smallest element, and on its own exchange. Then the rest of the elements found in the smallest element, the second element of the array with which the exchange of location, and so forth, until all elements of the array have been processed.

public static void sort(Comparable[] a) {
    int minIndex = 0;
    for (int i = 0; i < a.length; i++) {
        // min = a[i];
        minIndex = i;
        for (int j = i + 1; j < a.length; j++) {
            if (less(a[j], a[minIndex])) {
                // min = a[j];
                minIndex = j;
            }
        }
        exch(a, i, minIndex);
    }
}

Algorithms Features

The cost of sorting algorithms including both exchange and comparison of array elements.
Selection Sort exchange number is N, is equal to the size of the array.
Select the sort known from comparison of the number of execution of the algorithm process, the outer loop N times, each element of a line up, the next starting index of the inner loop plus 1, minus the number of comparisons 1, so a total of comparison ( N-1) + (N- 2) + ... + (1) = (N-1) * (N-2) / 2 times, ~ N ^ 2/2

Select the sorting algorithm is the square of the number of grade level growth, in addition to the algorithm as well as the following characteristics:

  • Running time and independent of the input
    in order to find the smallest element array and scan it again for the next scan does not provide any information, the sort of random elements of an array and sort the elements have been ordered array or array element values all of the same time used it's the same.
  • The number of mobile data sorting algorithm is the least of all
    select the number and size of the swap sorted array is a linear relationship, the subsequent learning of other sorting algorithms do not have this feature, most of the growth magnitude is logarithmic or linear square level.

Insertion Sort

When ordering the card, the general method used is the one by one to put the current this card into the appropriate positions already sorted the cards. Insertion sort of similar to this principle. The only difference is: when an element is inserted somewhere in the array, then all the elements of this position will need to move backwards one.

public static void sort(Comparable[] a) {
    for (int i = 1; i < a.length; i++) {
        for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) {
            exch(a, j, j - 1);
        }
    }
}

Algorithms Features

The time required for insertion sort is very much related to the characteristics of the input array, the fastest time possible in linear time is complete, the slowest time has reached the level of the square.
The best case only the input itself is ordered, then the outer loop will be performed N-1 times, each cycle will perform less (a [j], a [j - 1]), it is necessary to compare N-1 or , but the conditions for entering the inner loop are not met, the exchange 0 times.
The worst case is the reverse order of the input, then starting at index = 1, each element will be moved, and each comparator will correspond to a movement, the movement number of times equal to the comparison. Comparing the second element 1, 2 times more third, fourth, third, ... N-th N-1 Here, a total of about ~ N ^ 2/2 comparisons, ~ N ^ 2/2 times movement;
then in the case of random input elements, each element may be considered an average moving distance may be half of the array, required for comparison, the worst case number of moves is generally, from about ~ N ^ 2/4 comparisons, ~ N ^ 2 moving / 4 times.
Insertion sort of characteristics, determines that it is ideal for the practical application of the sort common in orderly array of parts.

Shell sort

Hill sorting improve insertion sort. For insertion sort order of magnitude increase in the square of random input level, for large-scale problems that the running time will be slower. Because the insertion sort would only swap adjacent element, the element can only move little by little from the current position to the position it should stay.
Hill has been improved for this sort of adds an element of movement span. Shell sort of thinking is to make any array element spacing h is ordered, this array is called an ordered array h. H a h a mutually ordered array is an ordered array of independent woven together to form an array. As shown below, h is 2, the array can be divided into two separate sub-array, after sorting the two sub-arrays, then the first sort, the entire array is ordered.

L   E   E   A   M   H   L   E  
L-------E-------M-------L      
    E-------A-------H-------E      

If h is large, it is possible to move to far away places. Hill sorting run, the first using larger coarse discharge h, and then decreases gradually according to certain rules h, when h is reduced to 1, to complete the final sorted array. What effect does this have to do, but will not be ordering several rounds of slower it? In fact Hill sorting much faster than insertion sort. This is because the scale and weigh Hill sorting order of sub-arrays, sorting place, each sub-array is very short, post-sorting sub-arrays and both are partially ordered, insertion sort in both cases are particularly Suitable for.
In order to achieve the following ordered Hill, h sequence selection of the most commonly used 3 * h + 1 sequences, i.e. 1,4,13,40,121,364,1093 ...

public static void sort(Comparable[] a) {
    int N = a.length;
    int h = 1;
    while (h <= N / 3) {
        h = 3 * h + 1;
    }

    while (h >= 1) {
        for (int i = h; i < N; i++) {
            for (int j = i; j > h && less(a[j], a[j - h]); j -= h) {
                exch(a, j, j - h);
            }
        }
        h /= 3;
    }
}

Algorithms Features

Select the sequence h impact on the performance of a large shell sort, shell sort, but a thorough understanding of the performance is still a challenge, there are a lot of different papers address a variety of sequences, but they can not prove a sequence is " the best".
Can intuitively feel time differences algorithm by comparing the three algorithms, the following processing time when comparing int array 100 000:

Selection, 37.595 s
Insertion, 76.14 s
Shell, 0.136 s

Thus, compared to Hill sort selection sort and insertion sort is much more efficient. For an array of medium-sized scale, Hill sort of run time is acceptable, some other more advanced algorithms may only sort Vigil twice as fast, but the code was more complicated algorithms. In no system available sorting algorithms available, or when writing code for embedded systems, consider using shell sort.

Guess you like

Origin www.cnblogs.com/zhixin9001/p/11415399.html