My Java development and learning journey ------ & gt; Hill sorting of Java's classic sorting algorithm, ------ java

Source: Internet
Author: User

My Java development and learning journey ------> Hill sorting of Java's classic Sorting Algorithm ------ java

I. Shell Sort)

Shell Sort is an insertion sorting algorithm named after D. L. Shell in 1959. Shell sorting is also called to narrow down incremental sorting.


Ii. Basic Ideas of hill sorting

The central idea of hill sortingThat is, grouping data and sorting each group of data. After each group of data is sorted, you can sort all groups by insertion. This can significantly reduce the number of exchanges to speed up sorting.

The central idea of hill sorting: first, take an integer less than n d.1 As the first increment, divide all records of the file into dOne group. All distance is dRecords with multiples of l are placed in the same group. Sort the inserted persons in each group first, and then take the second incremental d.2 <d1. Repeat the preceding grouping and sorting until the incremental d is obtained.T = 1 (dT <dT-l <... <D2 <d1), that is, all records are placed in the same group for direct insertion sorting.
This method is essentially a grouping insertion method.


Shell Sorting Algorithm Implementation:

Void ShellPass (SeqList R, int d) {// a sort in the hill sort. d is the current incremental for (I = d + 1; I <= n; I ++) // set R [d + 1 .. n] Insert the current ordered zone if (R [I]. key <R [I-d]. key) {R [0] = R [I]; j = I-d; // R [0] is only a temporary storage unit, not the Insert Location R [j + d]; = R [j] For the record do {// search for R [I]; // The record j = j-d; // search for the previous record} while (j> 0 & R [0]. key <R [j]. key); R [j + d] = R [0]; // insert R [I] to the correct position} // endif} // ShellPassvoid ShellSort (SeqList R) {int increment = n; // incremental initial value. Set n> 0 do {increment = increment/3 + 1; // calculate the next incremental ShellPass (R, increment ); // Shell insertion sorting with one increment of increment} while (increment> 1)} // ShellSort

Note:
When incremental d = 1, ShellPass and InsertSort are basically the same, but a cycle criterion "j> 0" is added to the InsertSort because there is no Sentel to prevent the subscript from crossing the border.



Iii. Hill Sorting Algorithm Analysis

1. Select an incremental sequence.

The execution time of Shell sorting depends on the incremental sequence. The common features of a good incremental sequence are as follows:

A. The last increment must be 1.

B. Try to avoid the mutual multiples of values (especially adjacent values) in the sequence.

A large number of experiments have been conducted to show the best results: WHEN n is large, the number of comparisons and moves is roughly between n ^ 1.25 and n ^ 1.26.


2. Shell sorting has better performance than direct insertion sorting.

The reason why the time performance of hill sorting is better than direct sorting is as follows:

A. When the initial State of a file is basically ordered, the number of comparisons and moves required for direct insertion sorting is small.

B. when the n value is small, the difference between n and n ^ 2 is also small, that is, the best time complexity O (n) and the worst time complexity O (n ^ 2) of direct insertion sorting) the difference is not big.

C. at the beginning of the hill sorting, there were large increases, many groups, and a small number of records in each group. Therefore, the direct insertion sorting in each group was faster, and then the incremental d (I) gradually reduced, the number of groups is gradually reduced, and the number of records of each group is gradually increased, but because the order of d (I-1) as the distance order, the file is closer to the orderly state, therefore, the new sorting process is faster. Therefore, the efficiency of hill sorting is much higher than that of direct insertion sorting.


3. Stability

Hill sorting is unstable.



Iv. algorithm drills
Assume that the files to be sorted are composed of 10 records. The keywords are 40, 38, 65, 97, 76, 13, 27, 49, 55, and 04. The incremental sequence values are as follows: 5, 3, and 1, as shown in the following figure:



Ps: You can also open the following link, set the array to be sorted, and perform sorting drills.

Hill sort animation demo (http://student.zjzk.cn/course_ware/data_structure/web/flashhtml/shell.htm)


V. Code Implementation


Public class ShellSortTest {private static void shellSort (int [] source) {int j; for (int gap = source. length/2; gap> 0; gap/= 2) {for (int I = gap; I <source. length; I ++) {int temp = source [I]; for (j = I; j> = gap & temp <source [j-gap]; j-= gap) source [j] = source [j-gap]; source [j] = temp;} System. out. print ("growth sequence:" + gap + ":"); printArray (source) ;}} private static void printArray (int [] source) {for (int I = 0; I <source. length; I ++) {System. out. print ("\ t" + source [I]);} System. out. println ();} public static void main (String [] args) {int source [] = new int [] {,}; System. out. print ("original sequence:"); printArray (source); System. out. println (""); shellSort (source); System. out. print ("\ n final result:"); printArray (source );}}


The running result is:


Original sequence: 4938659776132749554 growth sequence: 5: 1327495544938659776 growth sequence: 2: 4271349385549659776 growth sequence: 1: 4132738494955657697 final result: 4132738494955657697

It is found that the growth sequence is 5, 2, 1 and the requirements of the topic 5, 3, 1 are different. The files to be sorted by analysis are composed of 10 records, 10/2 = 5-2 = 3-2 = 1. The code above changes slightly to change the value of the growth sequence.

Run the following line of code in the shellSort (int [] source) method:

for (int gap = source.length / 2; gap > 0; gap /= 2) {
Changed:

for (int gap = source.length / 2; gap > 0; gap -= 2) {
Run the program again and print the result as follows:

Original sequence: 4938659776132749554 growth sequence: 5: 1327495544938659776 growth sequence: 3: 1344938274955659776 growth sequence: 1: 4132738494955657697 final result: 4132738494955657697


========================================================== ======================================

If you want to use the specified growth sequence to sort the specified array by Hill, you can modify the above program. The modified code is as follows:

Public class ShellSortTest2 {/*** array to be sorted */private int [] sources;/*** number of elements in the array */private int itemsNum; /*** incremental array sequence */private int [] intervalSequence; /*** @ param maxItems * array size * @ param intervalSequence * incremental array sequence */public ShellSortTest2 (int [] source, int [] intervalSequence) {this. sources = new int [source. length]; this. itemsNum = 0; // No element this. intervalSequence = intervalSequence;}/*** Hill Sorting Algorithm */public void shellSort () {int gap = 0; // incremental for (int iIntervalLength = 0; iIntervalLength <intervalSequence. length; iIntervalLength ++) // The outermost loop, determined by the number of incremental sequence elements {gap = intervalSequence [iIntervalLength]; // retrieves the corresponding growth sequence int innerArraySize from the incremental array sequence; // number of elements inserted for sorting each time. if (0 = itemsNum % gap) {innerArraySize = itemsNum/gap;} else {innerArraySize = itemsNum/gap + 1 ;} for (int I = 0; I <gap; I ++) {int temp = 0; int out = 0, in = 0; if (I + (innerArraySize-1) * gap> = itemsNum) {innerArraySize --;} // sort data by insert internally (int j = 1; j <innerArraySize; j ++) {out = I + j * gap; temp = sources [out]; in = out; while (in> gap-1 & sources [in-gap]> temp) {sources [in] = sources [in-gap]; in = in-gap;} sources [in] = temp ;}} System. out. print ("growth sequence:" + gap + ""); this. displayArray () ;}/ *** initialize the array to be sorted */public void initArray (int [] array) {for (int I = 0; I <array. length; I ++) {sources [I] = array [I];} itemsNum = array. length;}/*** display array content */public void displayArray () {for (int I = 0; I <itemsNum; I ++) {System. out. print ("\ t" + sources [I] + "");} System. out. println ("\ n");} public static void main (String [] args) {int [] intervalSequence = {5, 3, 1 }; int [] source = {49, 38, 65, 97, 76, 13, 27, 49, 55, 04}; ShellSortTest2 ss = new ShellSortTest2 (source, intervalSequence ); // initialize the ss array to be sorted. initArray (source); System. out. print ("original sequence:"); ss. displayArray (); // Hill sorting ss. shellSort (); System. out. print ("Final Result:"); ss. displayArray ();}}

The running result is as follows:

Original sequence: 49 38 65 97 76 13 27 49 55 4 growth sequence: 5 13 27 49 55 4 49 38 65 97 76 growth sequence: 3 13 4 49 38 27 49 55 65 97 76 growth sequence: 1 4 13 27 38 49 49 55 65 76 97 final result: 4 13 27 38 49 49 55 65 76 97


========================================================== ========================================================== ====================

Author: Ouyang Peng: Welcome to repost. sharing with others is the source of progress!

Reprinted Please retain the original address: http://blog.csdn.net/ouyang_peng

========================================================== ========================================================== ====================








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.