Data Structure (iii) Implementation of seven sorting algorithms in Java.

Source: Internet
Author: User
Tags array length sorts

Many times, listen to others in the discussion of quick sort, choose sort, bubble sort and so on, all feel very good, thought, crouching groove, sort also divided so many, feel others very good, actually, when we ourselves to learn to find, and did not imagine that difficult, Today, we summarize the implementation principles of various sorts and implement them.

-wh

An overview of the writing style of the article

Choose Sort, insert sort, bubble sort, merge sort, quick sort, hill sort, heap sort,

Finally, the various sorting algorithms are compared to clarify the advantages and disadvantages of various sorts.

The quick sort is the enhancement of the bubbling sort, the heap sort is the enhancement to the selection sort, the hill sort is the enhancement to the insertion sort, this is 6 kinds, the last one is the merge sort.

          

Second, choose the sort

Choosing sort is the simplest sort I think, because it's easy for us to think of this method of sorting arrays, which is very simple,

      

The schematic is as follows: first the number on the first bit value is compared to the number in all positions, and if the number in the first position is larger than the number in the second position, then the number in the first position is compared with the number in the third position, after a round of comparison, The number on the first bit value is the smallest of all the numbers, then the number in the second position is compared to the number in all positions thereafter, the same rule, after the second round of comparison, the second place is the second-smallest number in all numbers, then down, down, until the end of the last position. Sorting by this method is called selecting Sort.

Code implementation

            

Test

            

View Code

              

Dance: http://v.youku.com/v_show/id_XMjU4NTY5NTcy.html

Third, insert sort

Simply, given a set of records, divides it into two sequence groups, one for ordered sequences (from small to large in order or from large to small), one for unordered sequences, and the first in records as one data in an ordered sequence group, and all remaining numbers as data in unordered sequence groups. The data in the unordered sequence group is then compared to the records in the ordered sequence, starting with the second data in the record, and then inserted into the appropriate position in the ordered sequence group until the last data in the unordered sequence group is inserted into the ordered sequence group.

Schematic diagram

             

Code implementation

              

View Code

Very interesting video, insert sort of fun dance: http://v.youku.com/v_show/id_XMjU4NTY5MzEy.html

Four, bubble sort

Bubble sort is as simple as selecting sort, good understanding, the whole process is like bubble upward, assuming from small to large order, for a given N records, from the first record began to compare the adjacent two records, when the previous record is greater than the subsequent record, the exchange position, after a round of comparison, The nth bit is the largest number in the entire record, and then the second round of the first n-1 record is repeated until only one of the records for the comparison is left.

              

Code implementation

          

View Code

Bubble Sort: http://v.youku.com/v_show/id_XMzMyOTAyMzQ0.html

Five, merge sort

There are two implementations of merge sort, one is non-recursive and one is recursive, but I think if you understand the implementation of non-recursive, then you know the principle of merge sort, and recursion is very simple.

What is a merge sort? (We are explaining the 2-way merge sort)

A picture to understand what is called 2-way merge sort

               

Each element in an array is initially treated as an ordered sequence (with an array length of n), and then the adjacent two ordered sequences are combined into an ordered sequence, and the first merge can get an ordered sequence of N/2 lengths of 2 (the length of the last ordered sequence may be 1, or it may not be the key to see the number of elements in the array). , in the 22 merge, get N/4 a length of 4 ordered sequence (the last one may be less than 4) ... Always merge until you get an ordered sequence of N of length 1

Simply put, by three steps to solve three problems, you can write a merge sort

1, solve the adjacent two ordered sequences into an ordered sequence, very simple, add an array (the same length and the array to be arranged),

The core operation of the two-way merging, in the process of merging, may break the original ordered sequence, so, the result of merging into another array, set two adjacent ordered sequence is r[s] ~r[m] and r[m+1]~r[t], the two ordered sequences are merged into an ordered sequence, r1[s]~r1[ T], set three parameter i,j,k. I and J point to the first record of two ordered sequences, that is, i=s,j=m+1,k points to the location where the merge results are placed (that is, where the merge results are put in R1) k=s. Then, compare the number of records that I and J refer to, take out the smaller one as the result of the merge into the position of K, and then move the smaller point backward until all the records of one of the two ordered sequences are taken out, and the remaining record sequence of another ordered sequence is sent to the merged ordered sequence (that is, put into R1)

              

View Code

2, how to complete a trip to merge?

There's going to be a situation here, three cases,

Assume that the number of elements in each ordered sequence is H (h=1 of the first merge), i=0, starting with the first element. Merging each fetch two ordered sequence, then the span is 2h, the problem comes, as long as the length of n (n array of the largest subscript value) there are several such two ordered sequences, then you can do different operations.

First case: (i+2*h-1) <= N//For example, I=0,h=1, (i+2*h-1) means to point to the first two ordered sequence of the last position of the subscript value, with it to the N (n array of the largest subscript value) compared, if less than n, then there are other numbers behind , if equal to N, the end of the description, the entire array is exactly two ordered sequence, there will be no extra number. Then perform a merge, merge the two ordered sequences, then I plus 2h. If this condition is still met, continue to merge, if not, judge the other situation.

Second case: (i+h-1) < n//Description Finally there are two ordered sequences, but the length of the last ordered sequence is not H, it is also merged

The third case: (i+h-1) >= N//indicates that only the last ordered sequence is left, the ordered sequence is sent directly to the corresponding position of the R1.

            

View Code

3. Complete the merge sort

We solved two problems, one is how to merge the two ordered sequences, and the other is how to judge the completion of the merging process. Now we need to solve how to control the end of the two-way merger? That is how many trips need to be merged.

When the step is equal to n or greater than n, the description leaves only an ordered sequence, then the merge is over.

            

View Code

Six, quick sort

The quick sort is the enhancement to the bubble sort, the enhancement is: In the bubble sort, the record comparison and the movement is in the adjacent two positions, the record each exchange only then moves one position, therefore the total comparison number and the movement number, but the fast row record comparison and the movement is from the two ends to the middle, Larger records can be moved from the front to the back once, and smaller records can be moved from the back to the front one at a time, reducing the number of comparisons and moves

Quick Sorting principle: Select an axis value (comparison of the benchmark), the records to be sorted into separate two parts, the left record is less than or equal to the axis value, the right record is greater than or equal to the axis value, and then the left part and the right part to repeat the previous process, that is, the left section and select an axis value, Divided into two separate parts, this uses recursion. In the end, the whole sequence becomes orderly.

Question: How do I select an axis value? How do I turn a sequence into left and right parts?

There are three options for axis values:

1. Select a record at the first position of the sequence

2. Select a record at the middle of the sequence

3, compare the first and middle position of the sequence and the record at the end position, select a record with the center of the size,

How do I divide a sequence into two left and right parts?

Look at the diagram of the execution process, when a trip to compare down, the left and right side of the axis is lined up, which takes advantage of first and end two parameters, one starting from the beginning, one from the end, when two equals, the sequence of all the records are traversed once, The first comparison is the same as the first comparison of the selection sort, but then it starts to be different, because the element on the left side of the axis value does not have to be compared to the element to the right of the axis value, and the selection sort is compared to all.

            

            

Recursive invocation

              

View Code

Quick sort: http://v.youku.com/v_show/id_XMzMyODk4NTQ4.html

Vii. sort of Hill

The hill sort is actually an upgraded version of the Insert sort, which is essentially an insert sort operation, but the hill sort does not treat a set of records as a whole, but divides the entire record into groups of records, and then inserts the sort for each group of records.

The grouping rules are as follows: Suppose there are 1 2 3 4 5 6 7 8 9 100 positions (the number is placed in each position, the number is ignored, and the position is discussed). (The Insert sort operation is omitted, only the grouping is explained, and the complete hill sort is the insert sort operation after each grouping)

Steps are: 5, 3, 1

The first time is divided into 5 groups of records (the number of groups is the same as the step size): 1, 6, 2, 7, 3,8, 4,9, 5,10 These five sets of records, respectively, the five groups of records inserted sorting.

The second is divided into 3 groups of records: 1,4,7,10, 2,5,8, 3,6,9 These three sets of records, respectively, the three sets of records to insert the sort

The third time is divided into 1 groups of records: 1 2 3 4 5 6 7 8 9 10, insert sort for this set of records,

As long as the step to meet the last time is 1, and is from large to small. Generally used (array length/2) or (array length/3 + 1) to represent stride size.

The benefits of doing this are:

Divides the array elements to be sorted into groups, with a relatively small number of records in each group

After the first few sorts, the whole sequence becomes a "basic ordered sequence", and finally, a direct insertion of all elements is sorted.

Direct insert sorting is very efficient for sequences with a minimum of order and number of records, while the Hill sort takes advantage of these two points.

Schematic diagram

          

Explanation: The first group, 49,13, 38,27, 65,49, 97,55, 76, 45 groups, the five groups were inserted in the sorting, 49 found 13 o'clock, will be inserted sort, the position will be interchanged, instead of all groups first, the rear sequence.

The execution of the step is repeated until the step is 1 and after the last direct insertion, the entire hill sort is completed.

Run-time diagram: See the resources I share at the bottom. (I don't know how to upload a. swf file in the blog park, or how to upload a dynamic graph.) Helpless

Code implementation

             

View Code

    

Hill Sort Dance: http://v.youku.com/v_show/id_XMjU4NTcwMDIw.html

Eight, heap sorting

The above-mentioned hill sort is the enhancement of the insertion sort, then the heap sort, is to enhance the choice of sorting, choose to sort a data to be compared with each data, and did not take advantage of some comparative results, for example, 4 compared with 10, 3 and 4 compared, supposedly do not let 3 and 10 in comparison, But the choice of sorting does not have this intelligence, but rather an honest comparison, and heap sorting is the perfect use of the results of previous comparisons, thus increasing efficiency.

Before explaining heap sequencing, you must know what is a heap?

Heap is a completely binary tree, what is a complete binary tree? Only the bottom two levels of the node can be less than 2, and the bottom layer of the nodes are concentrated in the left-most position of the layer of the two-fork tree (still do not understand Baidu what is a complete binary tree)

This figure is a complete binary tree, but not a heap.

Heaps of two kinds, big top piles and small top piles

Big Top heap: On the basis of the complete binary tree, each parent node is larger than its own two sub-nodes, this is the large top heap, characterized by the root node is the largest value, see, 90:70, 80 large, 70:60, 10 large, and so on

                 

Small top heap: In contrast to a large top heap, the root node is the smallest value, and each parent is smaller than its own child nodes, such as

                

Heap sorting is the use of this feature of the heap to write, the principle: first a set of n elements of the sequence to build a large top heap or small top heap, in the root node on the number of the last number of the heap with the exchange, at this time, the nth digit is the entire sequence of the largest or smallest number, Then in the first n-1 bit elements are built into a large top heap or a small top heap, in the root node with the n-1 bit interchange, get the 2nd or 2nd small number, in the first n-2 the number of bits to build, and so on, until only 1 elements are left to end, sorting complete.

By explaining the principle: heap sorting is divided into three steps

1. Build large top pile or small top pile

2. Circulation

The root node and the end nodes are interchanged.

Build a large top heap or small top heap

3. Sorting complete

            

            

View Code

                  

Ix. summarize and compare the advantages and disadvantages of various sorting algorithms

                

          

1, note that the stability of the order means: example.

Before sorting: 5,6 (1), 1,4,3,6 (2), (first 6 before the second 6)

After sorting: If the sorted result is 1,2,3,4,5,6 (1), 6 (2) Then it is said that the sorting algorithm is stable, and vice versa is unstable

2, when the number of records to be sorted n large, and is unordered sequence, the stability is not required, the use of fast sorting is advisable

3, when the number of records to be sorted n large, memory space permitting, ordering stability, the use of merge sort is advisable

4, when the number of records to be sorted n large, and the sequence may appear in the case of a positive or reverse order, do not require stability, the use of heap sorting or merging is appropriate

5, etc... This directly to Baidu on a search, will certainly be summed up, and the summary is certainly better than me, I understand the various sorting algorithm principles, how to implement with Java, and basic features. Students who ask for a higher level of their own need to continue to study in depth.

Data Structure (iii) Implementation of seven sorting algorithms in Java.

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.