Algorithm (4th edition)-2.1 Primary sorting algorithm

Source: Internet
Author: User
Tags array length comparable sorts

2.1.1 Game rules

1. Sort the cost model: we need to calculate the number of comparisons and exchanges as we study the sorting algorithm. For algorithms that do not exchange elements, we calculate the number of times the array is accessed.

2.

· In-place sorting algorithm: In addition to the required stack of function calls and a fixed number of instance variables, there is no need for additional memory in-situ sorting algorithm;

· Other sorting algorithms: additional memory space is required to store another copy of the array.

2.2.2 Select sort

 Public classSelection { Public Static voidsort (comparable[] a) {//sort a[] in ascending order        intN = A.length;//Array Length         for(inti = 0; i < N; i++) {            //swap the smallest elements in a[i] and A[I+1..N]            intMin =i;  for(intj = i + 1; J < N; J + +)                if(Less (A[j], a[min])) min =J;        Exch (A, I, min); }    }    Private Static BooleanLess (comparable V, comparable W) {returnV.compareto (W) < 0; }    Private Static voidExch (comparable[] A,intIintj) {comparable T=A[i]; A[i]=A[j]; A[J]=T; }    Private Static voidShow (comparable[] a) {//to print an array in a single line         for(inti = 0; i < a.length; i++) Stdout.print (A[i]+ " ");    Stdout.println (); }     Public Static Booleanissorted (comparable[] a) {//test array elements for order         for(inti = 1; i < a.length; i++)            if(Less (A[i], a[i-1]))return false; return true; }     Public Static voidMain (string[] args) {//reads strings from standard input, sorts them, and outputsString[] A =in.readstrings ();        Sort (a); assertissorted (a);    Show (a); }}
Selection

1. Definition: First, find the smallest element in the array, and secondly, swap it with the first element of the group (if the first element is the smallest element then it is swapped with itself). Again, find the smallest element in the remaining element and swap it with the second element of the array. This is repeated until the entire array is sorted.

2. for an array of length n, it takes approximately N^2/2 and n times to select a sort.

3. The choice of sorting has two distinct features:

· Run time is irrelevant to input (an array with an ordered array or primary key is all equal and an array of randomly arranged arrays takes as long as the sort time);

· The data movement is minimal (the selection is sorted using N-switching-the linear level, the number of exchanges of most other algorithms-the linear logarithm or the square level).

2.2.3 Insert Sort

 Public classInsertion { Public Static voidsort (comparable[] a) {//sort a[] in ascending order        intN =a.length;  for(inti = 1; i < N; i++) {            //Insert a[i] into a[i-1], a[i-2], a[i-3] ... Among             for(intj = i; J > 0 && less (a[j], a[j-1]); j--) Exch (A, J, J-1); }    }    Private Static BooleanLess (comparable V, comparable W) {returnV.compareto (W) < 0; }    Private Static voidExch (comparable[] A,intIintj) {comparable T=A[i]; A[i]=A[j]; A[J]=T; }    Private Static voidShow (comparable[] a) {//to print an array in a single line         for(inti = 0; i < a.length; i++) Stdout.print (A[i]+ " ");    Stdout.println (); }     Public Static Booleanissorted (comparable[] a) {//test array elements for order         for(inti = 1; i < a.length; i++)            if(Less (A[i], a[i-1]))return false; return true; }     Public Static voidMain (string[] args) {//reads strings from standard input, sorts them, and outputsString[] A =in.readstrings ();        Sort (a); assertissorted (a);    Show (a); }}
insertion

1. differences from bubble sorting:

· Insert Sort: Inserts each element into an appropriate position in another already ordered element;

· Bubble sort: Pushes the remaining largest element to the right each time.

2. The time required to insert a sort depends on the initial order of the elements in the input.

3. For randomly sorted arrays with a length of N and a primary key that is not duplicated, insert sort:

· ~N^2/4 and ~N^2/4 times are required on average

· Worst case scenario requires ~N^2/2 comparison and ~N^2/2 switching

· Best case N-1 and 0 exchanges

4. Here are a few typical, partially ordered arrays:

· Each element in the array is not far from its final position.

· An ordered large array followed by a decimal group

· The position of only a few elements in the array is incorrect

Inserting a sort is useful for arrays like this, and choosing sort is not.

Visualization of 2.1.4 Sorting algorithm

1. The average number of comparisons required to insert a sort is only half the selected sort.

2.1.5 Comparison of two sorting algorithms

 Public classSortcompare { Public Static DoubleTime (String ALG, double[] a) {Stopwatch timer=NewStopwatch (); if(Alg.equals ("insertion") ) Insertion.sort (a); if(Alg.equals ("Selection") ) Selection.sort (a); //if (alg.equals ("Shell")) Shell.sort (a); //if (alg.equals ("Merge")) Merge.sort (a); //if (alg.equals ("Quick")) Quick.sort (a); //if (alg.equals ("Heap")) Heap.sort (a);        returnTimer.elapsedtime (); }     Public Static DoubleTimerandominput (String ALG,intNintT) {//Use the algorithmic alg to sort the array of T-length n        DoubleTotal = 0.0; Double[] a=NewDouble[n];  for(intt = 0; T < T; t++) {            //perform a test (generate an array and sort)             for(inti = 0; i < N; i++) A[i]=Stdrandom.uniform (); Total+=Time (ALG, a); }        returnTotal ; }     Public Static voidMain (string[] args) {String alg1= Args[0]; String Alg2= Args[1]; intN = Integer.parseint (args[2]); intT = Integer.parseint (args[3]); DoubleT1 = Timerandominput (Alg1, N, T);//total time for algorithm 1        DoubleT2 = Timerandominput (Alg2, N, T);//total time for algorithm 2stdout.printf ("for%d random doubles\n%s is", N, ALG1); stdout.printf ("%.1f times faster than%s\n", T2/T1, ALG2); }}/*java sortcompare insertion Selection 100For, random doubles insertion is 1.7 times faster than selection
    */
Sortcompare

This example runs the sorting algorithm specified by the first two command-line arguments, for the length n (specified by the third parameter).

1. For randomly sorted arrays with no duplicate primary keys, the run time of the insert sort and select sort is squared, and the ratio of the two should be a smaller constant.

2.1.6 Hill Sort

 Public classShell { Public Static voidsort (comparable[] a) {//sort a[] in ascending order        intN =a.length; intH = 1;  while(H < N/3) H = 3 * H + 1;//1, 4, 121, 364, 1093, ...         while(H >= 1) {            //Change Array to H order             for(inti = h; i < N; i++) {                //Insert a[i] into a[i-h],a[i-2*h],a[i-3*h] ... Among                 for(intj = i; J >= H && less (A[j], a[j-h]); J-=h) Exch (A, J, J-h); } h= H/3; }    }    Private Static BooleanLess (comparable V, comparable W) {returnV.compareto (W) < 0; }    Private Static voidExch (comparable[] A,intIintj) {comparable T=A[i]; A[i]=A[j]; A[J]=T; }    Private Static voidShow (comparable[] a) {//to print an array in a single line         for(inti = 0; i < a.length; i++) Stdout.print (A[i]+ " ");    Stdout.println (); }     Public Static Booleanissorted (comparable[] a) {//test array elements for order         for(inti = 1; i < a.length; i++)            if(Less (A[i], a[i-1]))return false; return true; }     Public Static voidMain (string[] args) {//reads strings from standard input, sorts them, and outputsString[] A =in.readstrings ();        Sort (a); assertissorted (a);    Show (a); }}
Shell

1. Thought: The elements that make an arbitrary interval of h in an array are ordered.

2. One of the main reasons to study the design and performance of the algorithm is to solve the problems that can not be solved by increasing speed.

3. the run time of the hill sort does not reach the square level. For example, the comparison of algorithm 2.3 is known to be proportional to n^ (3/2) in the worst case scenario.

4. Hill sort it is acceptable to run for a medium-sized array. It has a small amount of code and does not need to use additional memory space.

5. If you need to solve a sorting problem and no system sequencing functions are available (such as direct contact with hardware or code running in an embedded system), you can sort by Hill first and then consider whether it is worth replacing it with a more complex sorting algorithm.

Algorithm (4th edition)-2.1 Primary sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.