Structure and algorithm (3)-----bubble, select, insert Sort algorithm

Source: Internet
Author: User
Tags rounds

1. Bubble sort

The origin of the noun is very well understood, the General river in the bubble, the bottom just came out of the time is relatively small, with slowly floating to the surface will gradually increase.

The bubbling algorithm operates in the following rules:

①, comparing adjacent elements . If the first one is bigger than the second one, swap them both .

②, for each pair of adjacent elements to do the same work , from the beginning of the first pair to the end of the last pair. When this is done, the final element will be the maximum number (the first wave bubbles complete ).

③, Repeat the above steps for all elements, except for the last one .

④, continue repeating the above steps each time for fewer elements until there is no pair of numbers to compare.

  

  

  The code is as follows:

/  * bubble sort  *  / Public classBubblesort { Public Static int[] Sort (int[] Array) {         //  here for loop indicates how many wheels must be compared in total          for(inti = 1; i < Array.Length; i++) {            // Setting a token, if true, indicates that the loop has not been swapped, that is, the order is ordered and the ordering is complete .             BooleanFlag =true;  //  Here The For loop indicates the order of each round of the comparison participating elements subscript //  array[0......length-i for the current unordered interval //   J range is critical , this range is gradually shrinking , because each round of comparison will be the largest on the right side               for(intj = 0; J <array.length-i; J + +) {                if(Array[j] > array[j + 1]) { //If the previous element > the next element (then a position exchange is required) inttemp =Array[j]; 1. Place the first element in a temporary position Array[j]= Array[j + 1]; 2, the position of the second element, the forward adjustment array[j+ 1] =temp; 3, in the original storage in the temporary location of the elements, removed to put in the second position flag=false; }            }            if(flag) { Break; }            //The result of the sequencing of the first round isSystem.out.print ("section"+I+"The result of round sorting is:");        Display (array); }        returnArray; }    //Iterate through the display array     Public Static voidDisplayint[] Array) {         for(inti = 0; i < Array.Length; i++) {System.out.print (Array[i]+ " ");    } System.out.println (); }     Public Static voidMain (string[] args) {int[] Array = {4, 2, 8, 9, 5, 7, 6, 1, 3 }; //unordered array order isSystem.out.println ("the unordered array order is:");        Display (array); System.out.println ("-----------------------"); Array=sort (array); System.out.println ("-----------------------"); System.out.println ("the order of the arrays after bubbling sorting is:");    Display (array); }}

  The results are as follows:

  

It was supposed to be 8 rounds, and here we have only 7 rounds, because the 7th round is already an ordered array.

  Bubble Sort Explanation:

The bubble sort is made up of two for loops, and the first for loop variable i represents the total number of round comparisons that are required, and the second for loop variable J represents the subscript for each round of the element that participates in the comparison. 0,1,......,length-i ", because each round of comparisons will have a maximum value placed on the far right, so the number of elements per round is less than one, which is why the range of J is gradually reduced. It is not difficult to write a bubble sort quickly after you understand it.

  Bubble Sort Performance Analysis:

  Assuming that the number of array elements participating in the comparison is N, then the first round of sorting has a N-1 comparison, the second round has N-2, and so on, and so on, the summation formula for this sequence is:

(N-1) + (N-2) +...+1 = N (N-1)/2

When the value of N is very large, the algorithm compares the number of N2/2 times, ignoring minus 1.

Assuming that the data is random, it is possible to swap locations each time, possibly without swapping, assuming a probability of 50%, then the number of interchanges is N2/4. However, if the worst-case scenario is that the initial data is reversed, the position is swapped for each comparison.

The number of exchanges and comparisons is proportional to the N2. Because constants are not large in O notation, ignoring 2 and 4, the O (N2) time level is required for the bubbling sort run.

In fact, whenever you see a loop nested in another loop, we can suspect that the algorithm runs at O (N2) level, the outer loop executes n times, and the inner loop executes n times for each outer loop (or a few n times). This means that you need to perform a basic operation of N2 at approximately the same time.

2. Select sort

Select Sort is the smallest element that is selected each time from the data element to be sorted, stored at the beginning of the sequence, until all the data elements to be sorted are exhausted.

  is divided into three steps:

①, from the sequence you want to sort, find the element with the smallest keyword

②, if the smallest element found is not the first element of the sequence to be sorted, swap it with the first element

③, from the remaining N-1 elements, find the smallest element of the keyword, repeat (1), (2) steps, until the sort ends

  

The code is as follows:

 PackageCom.jkqiang.demo; // Select Sort  Public classChoicesort { Public Static int[] Sort (int[] Array) {         // The total to go through the N-1 round comparison          for(inti = 0; i < array.length-1; i++) {            intMin =i;  //First round considered the first element to be the smallest
Step 1, find the smallest element
// number of times to compare per round for(intj = i + 1; J < Array.Length; J + +) { //start with the second element and compare it to the smallest element if(Array[j] <Array[min]) {min= J; // record subscript for the smallest element currently found } }
//Step 2, swap the minimum value found and the value of I position if(I! =min) { inttemp =Array[i]; Array[i]=Array[min]; Array[min]=temp; }
//The result of the sequencing of the first round isSystem.out.print ("First" + (i + 1) + "turns the result after sorting:"); Display (array); } returnArray; } // iterate through the display array Public Static voidDisplayint[] Array) { for(inti = 0; i < Array.Length; i++) {System.out.print (Array[i]+ " "); } System.out.println (); } Public Static voidMain (string[] args) {int[] Array = {4, 2, 8, 9, 5, 7, 6, 1, 3 }; // unordered array order is System.out.println ("the unordered array order is:"); Display (array); System.out.println ("-----------------------"); Array=sort (array); System.out.println ("-----------------------"); System.out.println ("the order of the arrays after the selected sort is:"); Display (array); }}

  Operation Result:

  

  Select Sort Performance Analysis:

  The select sort and bubble sort performed the same number of comparisons: N (N-1)/2, but at most, only a nth exchange.

When the value of N is large, the number of comparisons is primary, so as with the bubble sort, the O (N2) time level is indicated by the large O. But because the number of options to sort the exchange is few, the choice of sorting is undoubtedly faster than the bubbling sort. When the value of N is small, if the exchange time is much larger than the selection time, then the selection sort is fairly fast.

3. Insert Sort

Direct insertion sort The basic idea is that each step is to insert a record to be sorted into an ordered sequence that is already in sequence until all elements have been inserted.

The insertion sort is also divided into direct insert Sort, binary insert sort, linked list insert sort, hill sort, etc., here we just take a direct insert sort to explain, later speak advanced sort.

    

  

  The code is as follows:

 PackageCom.jkqiang.demo; //Direct Insert sort  Public classInsertsort { Public Static int[] Sort (int[] Array) {        intJ;  //  starting with the element subscript 1, select the appropriate position to insert, since there is only one element labeled 0, which is ordered by default          for(inti = 1; i < Array.Length; i++) {            intTMP = Array[i]; // record the data to be inserted j =i;  while(J > 0 && tmp < ARRAY[J-1]) {//From the rightmost start of a sorted sequence, find a number smaller than itsARRAY[J] = array[j-1];//Backwardj--; } Array[j]= tmp;//existence is smaller than its number, insert        }        returnArray; }     //  iterate through the display array      Public Static voidDisplayint[] Array) {         for(inti = 0; i < Array.Length; i++) {System.out.print (Array[i]+ " ");    } System.out.println (); }     Public Static voidMain (string[] args) {int[] Array = {4, 2, 8, 9, 5, 7, 6, 1, 3 };  // unordered array order is System.out.println ("the unordered array order is:");        Display (array); System.out.println ("-----------------------"); Array=sort (array); System.out.println ("-----------------------"); System.out.println ("the order of the arrays after inserting the sort is:");    Display (array); }}

  Operation Result:

  

  Insert Sort Performance Analysis:

In the first round of sorting, it compares the most once, the second round up to two times, one analogy, the nth round, up to N-1 times. So there is 1+2+3+...+n-1 = N (N-1)/2.

Assuming that the insertion point is found in each round of sorting, on average only half of the total data item is actually compared, we divide by 2 to get: N (N-1)/4. Using large O notation requires roughly the O (N2) time level.

The number of copies is roughly equal to the number of comparisons, but the time spent on one copy and one exchange is different, so the insertion sort is a bit faster than bubbling, compared to random data, and slightly faster than the selection sort.

It is important to note that, if you want to sort in reverse order, then each comparison and movement will be done, this time will not be faster than bubble sorting.

4. Summary

The above three kinds of sorting, bubbling , selecting , inserting with large o notation all require O (N2) time level. bubbling sorting is not generally selected , although bubbling sort writing is the simplest, but the average performance is not to choose sort and insert sort well .

Select sort to reduce the number of exchanges to the lowest, but the number of comparisons is quite large. Select sort can be applied when the amount of data is small and exchange data is more time-consuming than comparing the data.

In most cases, inserting a sort is the best choice for three algorithms , assuming that the amount of data is small or basically orderly .

Later we will explain the advanced sort, and the time level of the large O notation will be smaller than O (N2).

Structure and algorithm (3)-----bubble, select, insert Sort 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.