Java Sorting algorithm

Source: Internet
Author: User

(i) (1) Direct insertion Sort

The basic idea of inserting a sort directly (straight insertion sorting) : In the set of numbers to sort, assume that the number of previous (n-1) [n>=2] is already in order, Now you want to insert the nth number into the ordinal number in front, so that the n number is also in order. This cycle is repeated until all the rows are in order.

complexity : Time complexity O (n2) , space complexity O (1)

stability : The insertion sort is stable, and the order of the two equal elements before and after the order is constant ( it is guaranteed that the first 2 equal digits of the order are the same before and after the sequence and after the ordering of their two. In a simple formalization, if ai = Aj, the AI is originally in position, the AI is still in front of the Aj position. )

structure Complexity and application : is a simple sorting method, not only for the sequential storage structure (array), but also for the link storage structure, but in the link storage structure for direct insertion of the sort, do not move the position of the element, but instead of the corresponding pointer changes.


The role of Sentinel
Additional records introduced in the algorithm r[0] are called Sentinel or Sentinel.
Sentinel has two functions:
① a copy of the R[i] before the search (insertion position) loop, so that the contents of r[i] are not lost due to the post-move of the record;
② Its main function is to "monitor" the subscript variable J in the lookup loop. Once crossed out (that is, j=0), because the R[0].key and their own comparison, the loop to determine the condition is not established so that the end of the search cycle, so as to avoid every time within the loop to detect whether J is out of bounds (that is, the loop to determine the condition "j>=1").
Note:
① in fact, all additional nodes (elements) that are introduced to simplify boundary conditions can be called Sentinels.
"Example" the head node in a single linked list is actually a Sentinel.
The ② introduces a sentinel, which reduces the time it takes to find the loop condition by about half, so the amount of time saved on a file with a large number of records is considerable. For an algorithm that is similar to sorting in such a way that it can be used very frequently, reduce its run time as much as possible. Therefore, we should not consider the Sentinels in the above algorithm as tricks, but should understand and grasp this technique deeply.


Java source code (successfully run):

[Java]View PlainCopyPrint?
  1. Public static void straightinsertionsort (int []array) {
  2. int  Sentinel, J;
  3. for (int i = 1; i < array.length; i++) {
  4. j = i- 1;
  5. Sentinel = Array[i]; //Sentinel bit   
  6. while (J >= 0 && Sentinel < Array[j]) {
  7. array[j+1] = array[j]; //Move the value greater than Sentinel to one unit after the whole   
  8. j--;
  9. }
  10. array[j+1] = Sentinel;
  11. }
  12. }

(2) Direct Insert sort

The Insert sort algorithm is an efficient algorithm for ordering a small number of elements. The insertion sort works similar to the way the cards are organized at cards, and when we start to draw, our left hand is empty, then one card is touched from the table and inserted into the right position of the left hand. To find the right position for this card, compare it to the hand that is already in the hands from right to left, regardless of when the hand is sorted.

Java implements the algorithm as follows:

Java code
  1. Public void insertsort (int a[]) {
  2. int length=a.length; //Array length   
  3. int               J; //position of current value
  4. int               i; //point to position before J
  5. int             key; //The value currently being inserted for sorting
  6. //start traversing the value from the second position of the array   
  7. for (j=1; j<length;j++) {
  8. KEY=A[J];
  9. i=j-1;
  10. //a[i] is larger than the current value, A[i] moves back one bit, vacated the position of I, so that the next cycle of the value of the move   
  11. while (i>=0 && a[i]>key) {
  12. a[i+1]=a[i]; //A[i] value is moved back   
  13. i--; //i Move forward   
  14. }//Jump out of the loop (find the middle position to insert or have traversed to 0 subscript)
  15. a[i+1]=key; //Inserts the current value into
  16. }
  17. }
public void Insertsort (int a[]) {int length=a.length;//array length int J;//The position of the current value int i;//position to J before int key;//The value to be inserted in the sort// When the position begins to traverse the value for (j=1;j<length;j++) {Key=a[j];i=j-1;//a[i] is larger than the current value, A[i] moves back one bit, vacated the position of I, so that the next loop value moves back while (i>=0 && A[i]>key) {a[i+1]=a[i];//a[i] value is shifted back i--;    I move forward}//jump out of the loop (find the middle position to insert or have traversed to 0 subscript) A[i+1]=key;    Insert the current value}}

The case diagram is as follows:

Insertsort the process on the array a={5,2,4,6,1,3}, the subscript of the array is now above the mega, and the value of the black box is key=a[j].

A[i] is the value to the left of A[j], each time the loop key is compared to a[i], if key<a[i], then a[i] moves to the i+1, and i--moves to the left until A[i]<=key or i<0 is found, at which point the key is inserted into the a[i+1].

Question 1:a[i] is the a[i+1] value overwritten the first time you move to the right, does it cause data loss?

A: No data loss, should be the first right before the i+1=j, at this time a[j] value exists in the key. Each right shift leaves a position for the next right shift or insert, which is where the key to the insertion sort is.

(b), select Sort? thought: Each trip selects the lowest-key record from the sequence of records to be sorted to the first position of the sorted table until all rows are completed. Key issue: Find the minimum key code record in the remaining sequence of records to be sorted. Method: – Direct Selection sort – heap sort ① Simple selection sort 1,    Basic idea: In the group of numbers to be sorted, select the smallest number to exchange with the first position, and then in the remaining number to find the smallest and second position of the number of exchanges, so loop to the penultimate number and the last number comparison. 2. Example 3, Java implementation
1  PackageCom.sort;2 3 //not stable4  Public classsimple selection of sort {5 6      Public Static voidMain (string[] args) {7         int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1,8};8System.out.println ("Before sorting:");9          for(inti = 0; i < a.length; i++) {TenSystem.out.print (a[i]+ ""); One         } A         //simple sort of selection -          for(inti = 0; i < a.length; i++) { -             intMin =A[i]; the             intN=i;//index of the minimum number -              for(intj=i+1;j<a.length;j++){ -                 if(a[j]<min) {//Find the smallest number -Min =A[j]; +n =J; -                 } +             } AA[n] =A[i]; atA[i] =min; -              -         } - System.out.println (); -System.out.println ("After sorting:"); -          for(inti = 0; i < a.length; i++) { inSystem.out.print (a[i]+ ""); -         } to     } +  -}

4. Analysis

Simple selection sorting is an unstable sort.

Time complexity: T (n) =o (n2).

(iii) bubble sorting : A record with a smaller key is like a bubble that floats on the go, a record of a larger key is like a stone sinking, and each trip has one of the largest stones sink.

The essence of the algorithm: (the maximum is the key point, definitely put to the last, so loop) each time from the first bit backward scrolling comparison, so that the maximum value sink, the minimum value rises one time, the last one forward (that is, the last to determine the maximum value no longer participate in the comparison, the number of comparisons minus 1)

Complexity: Time complexity O (N2), Space complexity O (1)

3. Java implementation

1  PackageCom.sort;2 3 //Stable4  Public classBubble Sort {5      Public Static voidMain (string[] args) {6         int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1,8};7System.out.println ("Before sorting:");8          for(inti = 0; i < a.length; i++) {9System.out.print (a[i]+ "");Ten         } One         //Bubble Sort A          for(inti = 0; i < a.length; i++) { -              for(intj = 0; j<a.length-i-1; J + +){ -                 //Here I mainly is each traverse once the largest I number sank to the bottom, there is no need to replace the the                 if(a[j]>a[j+1]){ -                     inttemp =A[j]; -A[J] = a[j+1]; -A[J+1] =temp; +                 } -             } +         } A System.out.println (); atSystem.out.println ("After sorting:"); -          for(inti = 0; i < a.length; i++) { -System.out.print (a[i]+ ""); -         } -     } -}
if the array is: int []nums = {5,4,3,2,1};the output for each round comparison is as follows:(1) 4,3,2,1,5,
(2) 3,2,1,4,5,
(3) 2,1,3,4,5,
(4) 1,2,3,4,5,
(5) 1,2,3,4,5,

4. Analysis

Bubble sort is a stable sort method.

If the first form of the file is a positive sequence, then a trip to the bubble can be sorted, sorting code is n-1, and there is no record movement, the time complexity is O (n)? If the file is in reverse order, it is necessary to n-1, each trip to n-i the comparison of the order code, and each time the comparison is moved three times, The comparison and the number of moves reached the maximum: O (n2)? Bubble sort Average time complexity is O (n2)

Java Sorting 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.