Java data structure and algorithm summary-bubble sort, select sort, insert sort algorithm analysis

Source: Internet
Author: User

  Preface: The position of the ranking in the algorithm naturally needless to say, in many jobs are used in the sort, like the student score statistics rankings, mall merchandise sales ranking, the news of the search heat rankings and so on. It is also because of the wide range of applications for sequencing, which has caused many people to delve into its interest, until today, there are many kinds of sorting algorithms. This post mainly introduces the common eight sorting algorithms, in general, different sorting algorithms in different scenarios have their own unique advantages, such as a simple bubble sort, select sort, insert sort not only the idea is simple, is conducive to our understanding, but also in the small-scale processing of data volume is not inferior. Next, we will analyze the advantages and disadvantages of each algorithm and the complexity of time.

All the code for this blog post has been uploaded to GitHub, corresponding to the project's Cn.codingblock.sort package under the exercise module: Https://github.com/lgliuwei/DataStructureStudy, Project Engineering for IntelliJ idea Environment, children's shoes may wish to download down, referring to the code to see the blog is not the effect of better ~ (the amount ~ because this project for the exercise project, the structure is more casual and there are duplicate code, reference when also please find: D)

First, bubble sort

Bubble sort is very simple, it is easy to understand, its logical thinking is like the water inside the bubble, the bigger the bubble, and hence the name bubble sort, its specific rules are as follows:

1, starting from the starting position of a set of data to compare the number of adjacent two,

2, if the previous number is larger than the next number of exchange position,

3, has been compared to the last number.

At this point, the last number of this set of numbers must be the largest, then the next round is so compared to the penultimate number, and then the next round compares to the third, so loop, until there is a round compared to the second number of the end, the final set of numbers is ordered.

On the code let the log demonstrate the process, the specific code is as follows:

1     /**2 * Bubble Sort3      * @paramNums4      */5      Public voidBubblesort (int[] nums) {6         intCount = 0;//Log Helper Code7          for(intout = nums.length-1; Out > 1; out--){8              for(intin = 0; in < out; in++) {9Logger.print ("compare" + nums[in] + "," + nums[in + 1]);Ten                 if(Nums[in] > nums[in + 1]) { One                     inttemp = nums[in+1]; ANUMS[IN+1] =Nums[in]; -Nums[in] =temp; -Logger.println (": Exchange:");//Log Helper Code theDisplay (Nums, in, in + 1);//Log Helper Code -}Else  { -Logger.println (": No Exchange");//Log Helper Code -                 } +             } -Logger.print (">>" + (++count) + "trip Bubbling:");//Log Helper Code +Display (nums);//Log Helper Code A         } at}

The logs are as follows:

Before sorting: 23, 52, 81, 69, 78, 32, 67, 70, 36, 73, Comparison 23, 52: Do not Exchange comparison 52, 81: Interchange comparison 81, 69: Exchange: 23, 52, [69], [81], 78, 32, 67, 70, 36, 73, Comparison 81, 78: Exchange: 23, 52, 69, [78], [81], 32, 67, 70, 36, 73, Comparison 81, 32: Exchange: 23, 52, 69, 78, [32], [81], 67, 70 , 36, 73, Comparison 81, 67: Exchange: 23, 52, 69, 78, 32, [67], [81], 70, 36, 73, Comparison 81, 70: Exchange: 23, 52, 69, 78, 32, 67, [70], [81], 36, 73, Comparison 81, 36: Exchange: 23, 52, 69, 78, 32, 67, 70, [36], [81], 73, Comparison 81, 73: Exchange: 23, 52, 69, 78, 32, 67, 70, 36, [73], [Bayi], >> 1th trip bubble: 23, 52, 69, 78, 32, 67, 70, 36, 73, 81, compare 23, 52: Do not Exchange comparison 52, 69: Do not exchange comparison 69, 78: Do not exchange comparison 78, 32: Exchange: 2  3, 52, 69, [32], [78], 67, 70, 36, 73, 81, Comparison 78, 67: Exchange: 23, 52, 69, 32, [67], [78], 70, 36, 73, 81, Comparison 78, 70: Exchange: 23, 52, 69, 32, 67, [70], [78], 36, 73, 81, Comparison 78, 36: Exchange: 23, 52, 69, 32, 67, 70, [36], [78], 73, 81, Comparison 78, 73: Exchange: 23, 5 2,---------------------------------------------------------2nd, 52, 69, 32, 67, 70, 36, 73, 78:81 Compare 69, 32: Swap: 23, 52, [32], [69], 67, 70, 36, 73, 78, 81, Comparison 69, 67: Exchange: 23, 52, 32, [67], [69], 70, 36, 73, 78, 81, Comparison 69, 70: Do not exchange comparisons 70, 36 : Exchange: 23, 52, 32, 67, 69, [36], [70], 73, 78, 81, Comparison 70, 73: No Exchange >> 3rd trip bubbling: 23, 52, 32, 67, 69, 36, 70, 73, 78, 81, Comparison 23, 52: No Exchange Comparison 52, 32: Exchange: 23, [32], [52], 67, 69, 36, 70, 73, 78, 81, Comparison 52, 67: Do not exchange comparisons 67, 69: Swap 69, 36: Exchange: 23, 32, 52, 67, [36], [69], 70, 73, 78, 81, Comparison 69, 70: No Exchange >> 4th trip Bubbling: 23, 32, 52, 67, 36, 69, 70, 73, 78, 81, 23, 32: No Exchange comparison 32, 52: Do not exchange comparisons 52, 67: Do not exchange comparisons 67, 36: Exchange: 23, 32, 52, [36], [67], 69, 70, 73, 78, 81, Comparison 67, 69: No Exchange >> 5th trip Bubble: 2 3, 32, 52, 36, 67, 69, 70, 73, 78, 81, Comparison 23, 32: Do not exchange comparison 32, 52: Interchange comparison 52, 36: Exchange: 23, 32, [36], [52], 67, 69, 70, 73, 7 8, 81, Comparison 52, 67: No Exchange >> 6th trip Bubbling: 23, 32, 36, 52, 67, 69, 70, 73, 78, 81, Comparison 23, 32: No Exchange comparison 32, 36: Not Exchange compare 36, 52: Do not Swap & gt;> 7th Trip Bubble: 23, 32, 36, 52, 67, 69, 70, 73, 78, 81, Comparison 23, 32: Do not exchange comparisons 32, 36: Do not exchange >> 8th trip Bubbling: 23, 32, 36, 52, 67, 69, 7 0, 73, 78, 81, sorted after: 23, 32,---------   

Time complexity of the bubble sort: O (n^2).

Through the analysis we can conclude that if the N data items are sorted, the first order in general is compared N-1 times, the second order compares N-2 times, and so on. So the number of times a bubble sort will be compared to n data items is:

(N-1) + (N-2) + (N-3) +....+ = N (N-1)/2 for convenience, approximate to compare (n^2)/2 times.

The constant is ignored by the large O notation, so its time complexity is: O (n^2).

Second, choose the sort

The selection sort is based on a bubbling sort of improvement, although the number of comparisons is still O (n^2), but it will have the necessary number of interchanges from O (n^2) to O (n) times, with the following collation:

1, from the array of 0 subscript start to mark the smallest,

2, starting from 1 subscript with the value of the tag under the comparison, if the value is less than the tag subscript is updated to assign the tag to 1 subscript, and so on and so on until the end of the array is traversed, and finally the 0 subscript and the minimum tag below the value of the exchange position.

3, and then from the array 1 small start comparison to the smallest, the second step of the analogy of the final Exchange 1 subscript and the minimum mark position. In turn ...

Select a sort of sequencing process (non-sorted entire):

Select the detailed code below:

1     /**2 * Select Sort3      * @paramNums4      */5      Public voidSelectionsort (int[] nums) {6         intmin;7          for(intout = 0; Out < Nums.length; out++) {8Min =Out ;9              for(intin = out + 1; In <nums.length; in++) {Ten                 if(Nums[in] <Nums[min]) { OneMin =in ; A                 } -             } -             inttemp =Nums[min]; theNums[min] =Nums[out]; -Nums[out] =temp; -         } -}

The time complexity for selecting sorting is: O (n^2).

Compared to bubbling, the choice of sorting greatly reduced the number of exchanges, but also compared with the same number of bubbles, so its time complexity is also: O (n^2).

Third, insert sort

The insertion sort is based on the idea of an orderly insertion, and you can understand the insertion sort in terms of the sequential insertions in the previous blog post, with the following approximate rules:

1, the most array of the 1 subscript starts to assign to the temporary variable, as the element to be inserted,

2, from the array of the 1 subscript forward traversal, all elements greater than the temporary variable is moved one bit, until the value is not greater than the temporary variable to insert a temporary variable into its next bit.

3, and then in the array from the 2 subscript to assign to the temporary variable, and from the 2 subscript forward traversal according to the second step encountered not greater than temporary variable when the temporary variable is inserted into it after a bit, and so on ...

The detailed code for the insert sort is as follows:

1     /**2 * Insert Sort3      * @paramNums4      */5      Public voidInsertionSort1 (int[] nums) {6         inttemp;7         intin ;8          for(intout = 1; Out < Nums.length; out++) {9temp =Nums[out];Tenin =Out ; One              while(In > 0 && nums[in-1] >temp) { ANums[in] = nums[in-1]; -in--; -             } theNums[in] =temp; -         } -}

Time complexity for inserting sorting: O (n^2).

For random data, the insertion sort speed is twice times the bubble sort, a bit faster than sorting, and the insertion sort is much better for basic ordered data, because while the conditions of the while loop are mostly not true when the basic ordered data is sorted, This is basically equivalent to just the outer layer of a loop, some ideally, the time complexity of inserting a sort can reach O (N), but typically, the average insertion time complexity is: O (n^2).

Iv. Summary

In addition to the three simple sort described above, there are merge sort, Hill sort, quick sort, cardinal sort, heap sort, and so on, these are advanced sort, slightly more complex, and use recursion, tree and other knowledge, so these sorts will be introduced in later blog post, the three sorts in this article are compared as follows:

  

Java data structure and algorithm summary-bubble sort, select sort, insert sort algorithm analysis

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.