Algorithms and data structures (13) of the primary sorting algorithm

Preface:

Sorting is a set of objects according to some logical order reordering process, such as credit card bill transactions are sorted by date - this sort is likely to use some sort algorithm, an early computer, we think that 30% of the calculation period is used in the ordering, if this ratio is reduced, probably one of the reasons is now more efficient sorting algorithm, the order of importance rather than reduced, now GF computer use makes the data everywhere, and organize your data first step is usually the sort;

Even if you only use the sort function in the standard library, learning sorting algorithms still has three practical significance;

  1. Analysis of sorting algorithms, helps to understand and comparative performance of the algorithm;
  2. Similar techniques also help solve other types of problems;
  3. Sorting usually the first step to solve the problem;

Primary sorting algorithm

下列代码展示了我们的习惯约定,将排序代码放在sort()方法中,该类还包含了辅助函数less()和exch();
public class Example {
    public static void sort(Comparable[] a){

    }

    private static boolean less(Comparable v,Comparable w){
        return v.compareTo(w)<0;
    }
    private static void exch(Comparable[] a,int i ,int j){
        Comparable t = a[i];
        a[i]=a[j];
        a[j]=t;
    }
    private static void show(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]+" ");
        }
        System.out.println();
    }
    public static boolean isSorted(Comparable[] a){
        for (int i = 1; i < a.length; i++) {
            if (less(a[i],a[i-1])) return false;
        }
        return true;
    }
}

Time complexity analysis:

Conclusion: For an array of length n, selection sort approximately n 2 / n times and 2 times Comparative exchange

Comparison (. 1-n) + (n-2) + (. 3-n) + ... + n = 2. 1 + (. 1-n) / 2 ~ n 2 on the n switching times, i.e. each index; / 2 comparisons the array will need to be exchanged;

Selection Sort

Idea: find the smallest element in the array, and it will be followed by the first element of the array of pseudo-swap only to find the second element of the remaining elements in the smallest, and the array exchange position again, and so forth, until the entire array sorting this method is called selection sort;

Features :( simple array of length n)

  1. Run time and independent of the input; a sort time as long as the latter has been ordered primary key all equal array and a random permutation array elements used;
  2. Minimum number of mobile data; only n times the exchange, which no other algorithms do not have this feature; (most of the growth in orders of magnitude are logarithmic or linear square level)
    public static void sort(Comparable[] a){
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int min = i;
            for (int j = i+1; j <n ; j++) {
                if (less(a[j],a[min])) min = j;
            }
            exch(a,min,i);
        }
    }

Insertion Sort

Idea: buy a card inserted into the appropriate position has ordered other cards in a computer-implemented, the default is the first order, in order to make room to insert elements, all the elements we need to rest are moved one to the right prior to insertion; this algorithm is called insertion sort;

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

Time Complexity Analysis: worst case all elements need to move the position, the best case is not required, i.e., the array is already sorted;

The worst case, with selection sort. n- 2 Comparison / 2, in the best case, comparisons for n-1, i.e. the cycle is not forj;

Consider partially ordered array; inversion refers to two elements in reverse order, such as in EXAMPLE 11 pairs have an inverted, EA XA XM XP XL ML ME PL PE LE; inverted if the number of array size of the array is less than some endorsement, then we say that the array is partially ordered; following several typical partially ordered array:

  1. Each element in the array a short distance from its final position;
  2. An ordered array of big pick a small array;
  3. Only a few elements in the array position is not correct;

Very effective insertion sort this array, selection sort is not, in fact, when the number of inversion, insertion sort may be faster than any other algorithm;

Shell sort

Fast sorting algorithms based insertion sort; scrambled for large-scale array, insertion sort is slow, as it can only switching the adjacent element, so the element only little by little from one end to the other end of the array, for example, if the smallest element in the primary key is just the end of the array, to be moved to its proper position n-1 times need to move, in order to speed Hill sorting improved simple and effective insertion sort, as well as the exchange of non-adjacent elements local array sort, insertion sort and finally with a partially ordered array sorting;

The core idea of ​​changing the number of inverted pairs!

How to change the number of inverted pairs? - that the array of any interval of h (custom, such as 3, 3 intervals) are sequential elements, such array is called h ordered array;

Array: h = 4

L E E A M H L E P S O L T S X R

L----------------------M----------------------P----------------------T

​ E----------------------H----------------------S----------------------S

And ---------------------- ---------------------- L O-- -------------------- X

​ A----------------------E----------------------L----------------------R

An array that is an array of four sub-array of ordered;

One way to achieve the sort Hill: h these independent sub-array sorting (insertion sort algorithm selection); and then gradually decreasing the value of h, a final h = 1; been sequenced;

code show as below:

 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 = h / 3;
        }
    }

Core code:

for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) {
	exch(a, j, j - h);
}

After comparing each value of j and jh, sorted h a team will h = h / 3; reduced the value of h, an insertion sort again, due to the reduction of the number of inverted, so the number is too large, and a randomly distributed array, the performance far more than the simple insertion sort of performance;

While the performance of the algorithm depends not only on h, but also on the mathematical properties between h; h for how to choose is not yet conclusive, what is the best;

Experienced programmers sometimes choose shell sort, so for an array of medium-sized, its running time is acceptable; it's code is very small and does not require additional memory space; plus other high efficiency algorithm, except for the big N, they may only sort Vigil twice as fast, if you need to solve a scheduling problem, but when there is no sort of system functions available, you can use shell sort, after service implementation, then consider whether it is worthwhile to replace it with other sorting algorithms more hair smashed;

Published 17 original articles · won praise 0 · Views 356

Guess you like

Origin blog.csdn.net/qq_32193775/article/details/104185262