Simple ordering of sorting algorithms (bubbling, selecting, inserting)

Source: Internet
Author: User

1. Basic Concepts

Internal sorting and external sorting

Depending on the sort process, whether the data to be sorted is all in memory, divided into two main categories:

Internal sorting: Refers to the sort process that the data to be sorted is stored in the computer's memory;

External sort: Refers to the sort process to which external memory is to be accessed in the sort.


Internal sorting is the basis of sorting, in the internal sort, according to the principle of sorting process can be divided into 5 categories: Insert sort, exchange sorting, select Sort, merge sort, according to the time complexity of the sorting process to divide, can be divided into simple sorting, advanced sorting. Bubble sort, simple selection sort, direct insert sort are simple sorting algorithms.


The criteria for evaluating ranking algorithms are two: the first is the arithmetic computation, which is mainly by comparing the number of records and the number of moves; the other is the number of additional storage units required to execute the algorithm.


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/74/99/wKioL1Yj086gnh8bAAB7_QjTO90832.jpg "title=" algorithm Classification " alt= "Wkiol1yj086gnh8baab7_qjto90832.jpg"/>


Note:

The algorithm in this paper is implemented using Java.

A lot of comments and printouts are used in the code so that you can see clearly and remove yourself when you use it.

For the sake of understanding, the implementation of Graph description algorithm is added.


2, Simple sorting algorithm implementation

2.1. Bubbling method

As the name implies, 22 comparison exchange, like blisters plump plump up, this idea is very intuitive.


Ideas:

Use ascending to illustrate.

The first scan, the data 22 comparison, the right value is not exchanged, if the left value is large, then the value of about 22 exchange position. Until N-1 and N are more than finished. This time after the scan, the maximum value is already on the far right.

The second round, from left to right continues to repeat the previous round of process, but compared to the previous round, the most right-most filter to exclude the maximum value within the range of the row. Other rounds are similar.


Code section

Package sort;import java.util.arrays;public class bubblesort {public static  void main (String[] args)  {int[][] tests = new int[][] { {  1, 9, 8, 5, 6, 7, 4, 3, 2 },{ 1, 2, 3,  4, 5, 6, 7, 8, 9 }, { 9, 8, 7, 6, 5, 4,  3, 2, 1 } };int[] test;for  (int i = 0; i <  tests.length; i++)  {test = arrays.copyof (tests[i], tests[i].length); BubbleSort1 (test) ;} for  (int i = 0; i < tests.length; i++)  {test =  Arrays.copyof (tests[i], tests[i].length); BubbleSort2 (test);}} /** *  per scan, push the maximum value to the right   re-scan again to reduce the comparison of the first and right values  */public static void bubblesort1 ( Int[] test)  {int swapvalue;int len = test.length;int count = 0;int count_exchange = 0; System.out.println ("========"); System.out.println ("Sort before:"  + arrays.tostring (Test));//  large number on right for  (int i = 0;  i < len - 1; i++)  {for  (int j = 0; j <  len - i - 1; j++)  {if  (test[j] > test[j + 1])  {swapvalue = test[j];test[j] = test[j + 1];test[j + 1] =  swapvalue;count_exchange++;} count++;}} System.out.printf ("The number of comparisons is%d\n the number of exchanges is%d\n after sorting:%s\n",  count, count_exchange,arrays.tostring (test)); System.out.println ("==========");} /** *  Improved:  Add a flag   If this scan, did not make any exchange, the data is the order that you want, directly exit  */public static void  BubbleSort2 (int[] test)  {boolean flag = false;int swapvalue;int len =  test.length;int count = 0;int count_exchange = 0; System.out.println ("========"); System.out.println ("Before Sorting:"  + arrays.tostring (Test));//  large number on right Do {len--;flag = false ;for  (int i = 0; i < len && len > 0;  i++)  {if  (test[i] > test[i + 1])  {swapValue = test[i]; test[i] = test[i + 1];test[i + 1] = swapvalue;flag = true; count_exchange++;} count++;}}  while  (flag); System.out.printf ("The number of comparisons is%d\n the number of exchanges is%d\n after sorting:%s\n",  count, count_exchange,arrays.tostring (test)); System.out.println ("==========");}}


Summarize:

Bubble method to a round of comparison.

However, the bubbling method can set a variable to determine if there is no exchange on this round to indicate that the data order conforms to the requirements and can immediately end the comparison.

So the worst case scenario is the reverse of the complete and target sequence, and the best case is the target order, which immediately ends the return.

Worst traversal N (n-1)/2, preferably traversing n-1.

The time complexity is O (n^2).



2.2, simple selection of sorting

Ideas:

Scan a given set of sequential data (left-to-right), find an extremum (maximum or minimum) at one end of a group (left or right), find a data, exclude it, and then scan it for a second time. That is, the second time is to exclude one end of the data that has been placed to find the extremum to scan the sort.

Consider here the scheme of finding the maximum value.

Assume that there is n number, define a temporary variable to place the maximum value of the index, after the first scan, after scanning the position n and the maximum index Exchange, let the maximum value at one end. Each subsequent scan excludes values that have been found to be placed at the end of the page.


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/74/99/wKioL1Yj2FzRPza9AAIsBbAgzDk495.jpg "title=" simple insert sort "alt=" Wkiol1yj2fzrpza9aaisbbagzdk495.jpg "/>


Improvement--Two Yuan Select sort

In each scan of the data, since all the numbers are to be compared, determine an extremum, whether the maximum and minimum values can be determined at the same time?

It's perfectly possible. And this reduces the number of iterations.

Question one, the number of iterations

The number of iterations seems to be halved, so how do you know? The number of elements is odd or even and halved. By analysis, the formula for halving is--the number of elements/2.

Note that this is an integer divided into integers, and the result is rounding.

Question two, position correction

When the maximum and minimum values are exchanged at the same index, be careful to fix the index that is found.



Code section

package sort;import java.text.messageformat;import java.util.arrays;/** *  Simple Selection sorting  */public class simpleselectionsort {public static void main (String[]  args)  {int[][] tests = new int[][] { { 1, 9, 8, 5,  6, 7, 4, 3, 2 },{ 1, 2, 3, 4, 5, 6, 7,  8, 9 }, { 9, 8, 7, 6, 5, 4, 3, 2, 1 } }; SimpleSelctSort1 (Tests[0]); SimpleSelctSort2 (tests[1]); SimpleSelctSort3 (tests[2]);} /** *  Simple sort   Assume that the number of elements is n  traversal number is  1+2+...+ (n-1) =n (n-1)/2  no less  */public  Static void simpleselctsort1 (int[] test)  {//  left-to-right scan, maximum value to the left int maxidx,  swapvalue, count = 0, round_count = 0; System.out.println ("= = Simple Sort 1==");for  (Int i = 0; i < test.length - 1; i++)  {system.out.println ("Run section"  +  (i + 1)  +  "wheel"); maxidx = i;round_count = 0;for  (int j = i + 1; j  < test.length; j++)  {if  (Test[j] > test[maxidx])  {maxIdx =  J;} round_count++;} if  (maxidx != i)  {swapvalue = test[i];test[i] = test[maxidx];test[ maxidx] = swapvalue; System.out.printf ("This round index  %d  and  %d  exchange location \ n",  i, maxidx);}  else {system.out.println ("This round does not have a swap position");} count += round_count; System.out.println ("This round comparison"  + round_count +  "Times". \ n The result of this round is "+ arrays.tostring (test)"); System.out.println ();} System.out.println (String.Format ("The number of comparisons is%d, the result of sorting is%s",  count,arrays.tostring (test)); System.out.println ("==========");//  there is a right-to-left scan and a large number in the left, in the right combination, here do not write code}/** * simplesort1 another realization   Scan from left to right, maximum to the right   it's a little awkward, exercise your mind,But the number of comparisons is no less  */public static void simpleselctsort2 (int[] test)  {int maxidx , swapvalue, count = 0, round_count = 0;int origin; System.out.println ("= = Simple Sort 2==");for  (int i = 0; i < test.length -  1; i++, system.out.println ("Run section"  + i+  "round, Comparison of this round"  + round_count +   "Times")  {maxidx = origin = test.length - 1 - i;round_count  = 0;for  (int j = 0; j < origin; j++)  {if  (test [J] > test[maxidx])  {maxidx = j;} round_count++;} if  (Maxidx != origin)  {swapvalue = test[origin];test[origin] = test[ Maxidx];test[maxidx] = swapvalue;} Count += round_count;} System.out.printf ("The number of comparisons is%d, the result of sorting is%s\n",  count, arrays.tostring (test)); System.out.println ("==========");} /** *  two USD Select sort   Whether each scan can handle 2 values at a time, maximum and minimum   left-to-right scan, maximum value to the left, minimum value on the right  */public static  Void simpleselctsort3 (int[] test)  {int maxIdx, minIdx, minOrigin;int  swapvalue;int count, round_count;count = round_count = 0;int len =  test.length; System.out.println ("= = two Yuan Select sort = =");for  (int i = 0; i < test.length /  2; i++, len--)  {maxidx = i;minorigin = minidx = len -  1;round_count = 0;for  (int j = i; j < len; j++)  {if  (Test[j] > test[maxidx])  {maxidx = j;}  else if  (Test[j] < test[minidx])  {minidx = j;} round_count++;} if  (maxidx != i)  {swapvalue = test[i];test[i] = test[maxidx];test[ maxidx] = swapvalue;// If the array is 1, 9, 2, 8, 5, 6, 7, 4, 3//  in this case 9 and 1 are exchanged, the following interchange will swap 9 and 3, So if you swap the minimum value, you need to fix if  (I&NBSP;==&NBSP;MINIDX) Minidx = maxidx;} if  (Minidx != minorigin)  {swapvalue = test[minorigin];test[minorigin] =  test[minidx];test[minidx] = swapvalue;} count += round_count; System.out.println ("Run"  +  (i + 1)  +  "round, this round comparison"  + round_count +   "Times"); System.out.println (arrays.tostring (test));} System.out.println (Messageformat.format ("The number of comparisons is {0}, the result of the sorting is {1}",  count,arrays.tostring (test)); System.out.println ("==========");}}


Summarize:

Simple sorting, all the data must be scanned n-1 times. No less than once. Whether or not the order is required, continue to compare.

The number of traversal is 1+2+...+ (n-1) =n (n-1)/2, Time complexity O (n^2).

The choice of sorting reduces the number of exchanges and improves efficiency.

Performance is slightly better than the bubbling method.



2.3. Insert Sort

For an ordered sequence of numbers, it is required to insert a number in it, requiring that the number is still ordered after insertion.


Basic idea of inserting sort:

Each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is inserted.

1, assuming from left to right, from small to large arrangement. Constructs a sequence A, its index 0 disposition is empty, the index starts from 1 to place to sort the sequence.

2. Place the value of the current index I a[i] at index 0 as the Sentinel value x, comparing the previous i-1 value at the current index a[i-1] and the Sentinel value X.

3, if the a[i-1]>x is not established, then the 5th step.

4, If the a[i-1]>x is established, it will i-1 the value of the right to the position of I, is covered.

Continue to the left i-2 the number of positions A[i-2] and x comparison size, greater than the right to move the overlay, not greater than the stop comparison.

5, put the Sentinel value in the gap after the right shift of the data.


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/74/9D/wKiom1Yj2b-i1poNAAMO9AmlBgg658.jpg "style=" float: none; "title=" Insert sort 1 "alt=" wkiom1yj2b-i1ponaamo9amlbgg658.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/74/99/wKioL1Yj2ebyJubJAAM7UTujaEA640.jpg "style=" float: none; "title=" Insert sort 2 "alt=" Wkiol1yj2ebyjubjaam7utujaea640.jpg "/>


Code section

package sort;import java.util.arrays;public class insertionsort {/** *  Insert Sort   Final sort from left to right, from small to big   ideas:  index 0 position set Sentinel, that is, a copy of the value to be compared in this round  *  starting from the previous position of the value to compare, compared to the Sentinel value, if greater than the sentinel value of the right shift, Then continue to compare; *  if not greater then stop compare   Place the position value of index 0 into the empty space after the right shift  */private static void insertsort ( Int[] arr)  {if  (arr == null | | &NBSP;ARR.LENGTH&NBSP;&LT;&NBSP;2)  {return;} int i, j;for  (i = 2; i < arr.length; i++)  {//  The value of the current position is placed at the first position as Sentinel arr[0] = arr[i];//  if the previous value is greater than the Sentinel value, move right. Then continue to see if the value on the left is greater than the Sentinel value j = i - 1;//  if it is less than the direct next round if  (Arr[j] > arr[0])   {for  (;  arr[j] > arr[0]; j--) arr[j + 1] = arr[j];//  Place the Sentinel value in the left-hand slot arr[j + 1] = arr[0]; //  pay particular attention to j+1, because j--has lost more than one 1}system.out.println ( Arrays.tostring (arr));}} Public static void main (string[]  args)  {int b[] = new int[] { 0, 3, 8, 5, 7, 2,  4, 9, 6, 1 };insertsort (b);}}


Summarize:

The role of Sentinel:

Keep the value of the comparison to compare in each round

Comparison with Sentinel can prevent the index of query criteria from overstepping, and improve the efficiency of conditional judgment in the loop.


The time complexity is O (n^2) stable sorting method. Performance is slightly better than the first two algorithms.



This paper simply describes the idea of a simple sorting algorithm and the implementation of the algorithm, this is just a beginning, subsequent will continue to complete other algorithms of the blog.

Finally, the problem of large-volume data sorting is introduced, and the MapReduce based on Hadoop is implemented.


This article from "The End of Nanshan" blog, declined to reprint!

Simple ordering of sorting algorithms (bubbling, selecting, inserting)

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.