Java Data structures and algorithms (iii)--bubbling, selecting, inserting sorting algorithms

Source: Internet
Author: User
Tags rounds

Previous blog Our implementation of the array structure is unordered, that is, purely in order of insertion sequence, then how to order the elements, this blog we introduce a few simple sorting algorithm.

1. Bubble sort

The origin of this noun is very good understanding, 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, this physical law I do not explain too much, we just need to understand.

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 (that is, the first wave bubbling is done).

③, 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:

Package Com.ys.sort;public class Bubblesort {public static int[] Sort (int[] array) {//Here the For loop represents the total number of rounds for which to compare (int i = 1; I & Lt Array.Length; i++) {//Set a tag, if true, indicates that the loop has not been exchanged, that is, the order is ordered and the ordering is complete. Boolean flag = true;//Here The For loop indicates that each round of comparison participates in the element subscript//To the current unordered interval array[0......length-i] to sort//j range is critical, this range is gradually shrinking, Because each round compares the largest on the right for (int j = 0; J < Array.length-i; J + +) {if (array[j]>array[j+1]) {int temp = array[j];array[j] = arr Ay[j+1];array[j+1] = Temp;flag = false;}} if (flag) {break;} The result of the sequencing of the first round is System.out.print ("+i+" round the result is: ");d isplay (array);} return array;} Traverse the display array public static void display (Int[] array) {for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]+ ""); }system.out.println ();} public static void Main (string[] args) {int[] array = {4,2,8,9,5,7,6,1,3};//unordered array order is SYSTEM.OUT.PRINTLN ("unordered array Order:"); Display (array); System.out.println ("-----------------------"); array = sort (array); System.out.println ("-----------------------"); System.out.println ("After bubbling sorted array order:");d isplay (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 indicates that each round of the element that participates in the comparison is labeled "0,1,......,length-i" because a maximum value is placed on the right side of each round. So the number of elements per round is less than one, which is why the range of J is gradually decreasing. 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 from the data element to be sorted each time, 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 to be sorted, find the element with the smallest keyword

②, if the smallest element is not the first element of the sequence to be sorted, swaps 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:

Package Com.ys.sort;public class Choicesort {public static int[] Sort (int[] array) {//A total of N-1 rounds to compare for (int i = 0; i < arr Ay.length-1; i++) {int min = i;//the number of times each round needs to be compared for (int j = i+1; J < Array.Length; J + +) {if (Array[j]<array[min]) {min = j;//records the minimum value currently found The subscript of the vegetarian}}//will find the minimum value and the value where I position is exchanged if (i = min) {int temp = Array[i];array[i] = array[min];array[min] = temp;} The result of the sequencing of the first round is System.out.print ("i+1" + "round the result of sorting:");d isplay (array);} return array;} Traverse the display array public static void display (Int[] array) {for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]+ ""); }system.out.println ();} public static void Main (string[] args) {int[] array = {4,2,8,9,5,7,6,1,3};//unordered array order is SYSTEM.OUT.PRINTLN ("unordered array Order:"); Display (array); System.out.println ("-----------------------"); array = sort (array); System.out.println ("-----------------------"); System.out.println ("The sorted array order after selection is:");d isplay (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 on the advanced sort will be the other.

    

  

  The code is as follows:

Package Com.ys.sort;public class Insertsort {public static int[] Sort (int[] array) {int j;//start with an element labeled 1 to select the appropriate location to insert, Because there is only one element for subscript 0, the default is ordered for (int i = 1; i < Array.Length; i++) {int tmp = array[i];//records the data to be inserted j = i;while (J > 0 && ; TMP < ARRAY[J-1]) {//from the rightmost beginning of the sorted sequence, find a number smaller than its array[j] = array[j-1];//backward nudge j--;} ARRAY[J] = tmp;//exists smaller than its number, insert}return array;} Traverse the display array public static void display (Int[] array) {for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]+ ""); }system.out.println ();} public static void Main (string[] args) {int[] array = {4,2,8,9,5,7,6,1,3};//unordered array order is SYSTEM.OUT.PRINTLN ("unordered array Order:"); Display (array); System.out.println ("-----------------------"); array = sort (array); System.out.println ("-----------------------"); SYSTEM.OUT.PRINTLN ("After inserting sorted array order:");d isplay (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).

Java Data structures and algorithms (iii)--bubbling, selecting, inserting sorting algorithms

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.