Java Sorting algorithm

Source: Internet
Author: User

Finishing system when found the original write a summary of the various algorithms, looked at, surprised, then I still so hard, specific algorithms, some have been blurred even forget, look at the time to put the content out, by the way in the familiar, after the time you can directly come to excerpt. The following is a summary of several commonly used sorting algorithms:

    • Insert Sort
    • Quick Sort
    • Bubble sort
    • Heap Sort
    • Count sort
    • Bucket sort

Maybe everyone on the insertion sort, quick sort, bubble sort more commonly used, in meeting the needs of the time is also simple, the following one to say the implementation of each algorithm, not guaranteed to write the most efficient, but to ensure that the central idea of various algorithms is right, we understand the spirit can:

 Insert Sort:

Insert sort the most real scene in life is in the time of playing cards, especially when the landlord is used most frequently, we unconsciously use this algorithm every day, so please do not tell everyone you do not algorithm, come to us all to relive that warm moment, first home to move cards, as the more intelligent people, Hand Jiyan fast person, I like not to look at the card, knock into a pile, finally, this with the sorting algorithm has no hair relationship, skip, all grab after looking at the card. From left to right, looking at what card to catch, a look, the first lap caught a 5, the second lap to a 2, if there is obsessive-compulsive disorder, cards must be in order, due to the order of emissions, so to meet, if you left the first card points less than the number of points you grab, then the left all the cards are less than the number of points, At this time you will compare, 5>2 (number of arguments), and then your hand is 2---5, the third lap of 4, the cards are very small, when you take 4 and 5 ratio (or 2 than the same), 4<5, then 4 should be on the left of 5, now the order is 2---4---5, Because it is not sure whether the number of cards on the left of 4 is less than 4, all to find the location on the left of the first less than 4 points, put 4 on the right side of this point, good coincidence 2<4, so now the order is determined to 2---4---5, fourth round catch a 3, are too small, But still need to put 3 into the corresponding position, first 3<5, then put to the front of 5, the order is temporarily 2---4---3---5,3 continue to look to the left, know to find a card smaller than it, then it and 4 comparison results for a temporary 2---3---4---5, and then in contrast with 2, The result, the order is 2---3---4---5, and so on, unconsciously completed the insertion sorting algorithm.

The process is like this, let's look at how it's implemented in code:

1 public void sort (int[] data) {2 for     (int j = 1; j < Data.length; J + +) {3          int i = j-1; 4          int key = Dat A[J]; 5 while          (i >= 0 && data[i] > key) {6             data[i + 1] = Data[i]; 7             data[i] = key; 8             I-= 1; 9
   }    11}

Since I'm using arrays to do this, the subscript starts at 0, so it might seem weird, which makes the code look a little bit difficult to understand,

  第2-10: The loop is the process of our looking at the card, why from the beginning, because it is not compared when looking at the first one, let's think it (point 5) is the smallest,

  Line 3rd: The meaning is to tell me that the current look at the card will be compared with the position of the card (should be compared with the card in the position of the place to see now), my second catch is 2, he would like to compare with the first one,

Line 4th: Look at this card is what points.

  Line 5th: If there is no more than the head, the number of points before cutting a position is greater than the number of points in this card, then the two of them change position.

第6-7 Line: swap position.

Line 8th: Since the position of the card moved forward one, then the next time to do the position of the comparison card to move a bit.

OK, the insertion sort is simple enough to say here. Suitable for use in cases where the amount of data is small.

  

  

  Quick sort:

    Please forgive me my life experience is not high, fast sequencing I really can not find the right life of the application scenario, just draw a small picture to illustrate it:

0 1 2 3 4 5 6 7
1 6 8 4 1222 29 872 5

The data is used for sorting, and the quick sort is done by splitting the array to be sorted, then sorting it locally, and at the beginning of the program the value stored in the left and last position of the array as the array "watershed" to be sorted, that is, the number smaller than this value is placed on the left side of this number, A number larger than this number is placed to the right of the number. How this is achieved, is nothing more than two aspects, comparison and position adjustment.

All the data in the array needs to be compared, if necessary, then adjust the position, adjust the position is divided into active adjustment and passive adjustment of two cases.

Active Adjustment:

Two conditions are required: (1) A data value that is less than the last position saved. (2) The value saved in the position in front of the position is greater than the value saved at the last position.

Actively adjust the time to save the last one has been compared to know that the saved value is less than the last position of the saved data value position of the next bit, is not particularly awkward, the above example of the above table above the number is the corresponding array subscript, at the time of the first comparison, compare 1 <5, the front does not have a value greater than 5, the position does not change, 6>5, do not change, 8>5, also do not have to change, 4<5, and in the position of the coordinates of 1 to save the value of 6, all 4 need to actively adjust, at this time The last one has been compared to know that the saved value is less than the last position of the saved data value position is 0, to say 4 is saved in the position of 1, but 1 of the location of the value is 6, all 6 will do the passive adjustment.

Passive adjustment:

Because the position of itself is about to be occupied by others, the adjustment is made. The passive adjustment position is and initiates the active adjustment the data carries on the position interchange, finally will initiate the active adjustment the value to save to the empty coordinates, the value that occurs after the movement can be believed to be bigger than the last subscript the value which the index saves, otherwise has already been actively adjusted. If it is still not good to understand then take this example: in comparison to 4, the need to adjust, the need for passive adjustment of the starting position of the subscript is 1, the active adjustment of the value of the subscript is 3, then the small mark 3 saved value 8 for the position swap, after the result is:

0 1 2 3 4 5 6 7
1 4 8 6 1222 29 872 5

After the first round of comparisons, we found that there was no need to adjust the position of the time, it should be adjusted to the last subscript to save the position of the value, because the previous said in the array to take the next position of the saved value as the array "watershed" So you should be aware of the need to mark 7 to save the value of 5 active to the subscript subscript 2 position. Then adjust the position. The adjustment method has been said before, no repetition. The final result is as follows:

  

0 1 2 3 4 5 6 7
1 4 5 6 1222 29 872 8

The next array to allocate is divided into two parts:

  

0 1 2
1 4 5

3 4 5 6 7
6 1222 29 872 8

The two parts are re-operated, so the quick sort needs to be computed in a recursive way. Here are a few variables that need to be saved to illustrate:

First: Is the last value, because the position of the array subscript is overwritten when the value is actively adjusted. As in the previous example, subscript 7.

Second: the subscript K of the data being compared with the last value, save K is the position to move to after the comparison in case a position adjustment is needed.

Third: has been compared with the left after a coordinate saved values, clear do not need to adjust the position of the last array subscript I, save this variable is because, if the next K subscript elements need to adjust the position, you need to i+1 the value of subscript and K subscript value interchange.

  

Let's take a look at the code implementation of the fast sorting algorithm:

 1 public void sort (int[] data) {2 quickSort (data, 0, data.length-1); 3} 4 5 public void QuickSort (in t[] data, int p, int r) {6 if (P < r) {7 int q = partition (data, p, r); 8 QuickSort (d ATA, p, q-1);         9 QuickSort (data, q + 1, R),}11}12 public int partition (int[] data, int p, int r) {14 int x = data[r];15 int i = p-1;16 for (int j = p; j <= R; j + +) {if (Data[j] &lt ; X && I < j) {i++;19 int key = data[j];20 Data[j] = data[i];2                 1 Data[i] = key;22//if (i! = j) {//data[i] + = data[j];24         DATA[J] = data[i]-data[j];25//data[i]-= data[j];26//}27}28  }29 int key = x;30 Data[r] = data[i + 1];31 data[i + 1] = key;32//if ((i + 1)! = R) {34//Data[i + 1] + = data[r];35//Data[r] = data[i + 1]-data[r];36//Data[i + 1]-= data[r];37 }38 1 + i;40}

If it is possible to make clear the part of the interchange position of the annotation part, especially judging the condition, then we really understand the fast sorting method. In the example, the Quicksort method implements recursive invocation, and the important method is partition, which completes the split sorted array, and the position adjustment operation.

In partition, we use X to save the value to compare. Using I to save the identified subscript that does not require a position adjustment, starting from 1, use J to save the array subscript of the value being compared for validation, starting with 0.

  

  Bubble Sort:

  This should be the most common, probably the final face of the set to be sorted start, with the first element in order and the previous comparison, if smaller than the previous, then the swap position, and then in front of a comparison, until the comparison to a position (this position before the value must be less than the value being compared). So also need to use two variables, a to mark the comparison of the value of the subscript, a to save the "position", guess everyone knows, so for bubble sort is not much nonsense, on the code:

1 public     void sort (int[] data) {2 for         (int i = 0; i < data.length; i++) {3 for             (int j = data.length-1; J > i + 1; j--) {4                 if (Data[j-1] > Data[j]) {5                     data[j-1] = data[j-1] + data[j]; 6                     data[j] = data[j-1]-Data [j]; 7                     Data[j-1] = data[j]; 8                 } 9             }10         }11     }

Very simple.

  Heap Sort:

I have to say, heap sort I have no recollection, see for a while to see understand, after seeing, I have to invent heap to find the person very worship, how good algorithm.

  In general, the heap sort is to find a maximum value in the array A[0.....N], then put Max Max to the last A[n]=max of the array, then find a maximum value from a[0.....n-1], then save the maximum value in a[0.....n-1], and so on. The key to heap sequencing is how to find the maximum value within a range as quickly as possible.

  Heap sorting is the maximum heap that is found by the maximum value, and some concepts are understood first:

Binary heap: Just understand the two-pronged tree on the line.

Maximum heap: satisfies all of the parent > child.

Minimum heap: satisfies all child > parent.

The first thing to do is to construct the array to be sorted into a binary heap, a hypothetical one, such as an array of sorts:

  

0 1 2 3 4 5 6 7
1 6 8 4 1222 29 872 5

Then we construct the following two-fork heap by the imagination, the method of constructing two fork heap is very simple, it is constructed in the way of binary tree from the beginning, and the result is as follows:

  

Through the construction of the two fork heap we need to draw useful information for us, useful information refers to each element in the binary heap in the child node in the array of coordinates, know that the binary tree people do not have to look at the second Fork heap know node I sub-node subscript should be 2*i+1, has 2 (i+1), because We are counting from subscript 0 . The number is the description of the binary pile by subscript.

After the construction of the binary heap is complete, then let's say how to construct the two-fork heap into the largest heap, constructed by using A[i] and his two children a[2*i+1],a[2 (i+1)] (if present) to compare the largest value of A[i],a[2*i+1],a[2 (i+1)] with a [i] position interchange, so where do I start counting? It is very simple to find the last node with children, because we are starting from 0, then the subscript should be from a.lenth-1/2 to 0, such a round down a[0] is the maximum value, code implementation:

 1 package sort; 2 3/** 4 * O (NLGN) constructs the data illusion into a binary heap, and the left and right coordinates of each node are 2i,2i+1.     Construct Max Tree: 5 * 6 * @author Think 7 * 8 */9 public class Heapsort implements Isort {Ten int datalength = 0;11 12         /***13 * Take the maximum value out, put it to the last, and then 1--n-1 the data to find the new maximum of */15 @Override16 public void sort (int[] data) {17             Datalength = data.length;18 buildmaxheap (data), n for (int i = dataLength-1; I >= 1; i--) {20 Data[i] + = data[0];21 data[0] = data[i]-data[0];22 data[i]-= data[0];23 datal  Ength--;24 max_heapify (data, 0); 25}26}27 28/**29 * Guaranteed binary heap Properties A[i] >= A[left[i]] a[i]     >= a[right[i]]30 * In the construction of the two fork heap and each time from the last removed an element will be re-organization of the structure of the two fork heap * * @param data33 * @param i34 */35  public void Max_heapify (int[] data, int i) {$ int largest = 0;37 int l = 2 * i + 1;38 int r = 2 * (i + 1); if (L < datalength && Data[l] > DaTa[i]) {largest = l;41} else {largest = i;43}44 if (R < Datalen             Gth && Data[r] > data[largest]) {largest = r;46}47 if (largest! = i) {48 Data[i] + = data[largest];49 Data[largest] = data[i]-data[largest];50 data[i]-= Data[large st];51 max_heapify (data, largest); 52}53}54 55/**56 * Build Maximum heap * * @param d Ata59 */60 public void Buildmaxheap (int[] data) {(Int j = ((dataLength-1)/2); J >= 0; j--) {max_heapify (data, j); 63}64}65}

In the Sort method, the maximum heap is constructed, the maximum value obtained by the maximum heap a[0] is swapped with the value saved by the last subscript of the A array, and then the maximum value is excluded from the data that constructs the largest heap. The exclusion is done by setting the bounds of the maximum heap time array, in which case the DATALENGTH variable is the function.

The Buildmaxheap method is to construct the largest heap for the first time, and you may have questions about how to call the Max_heapify method in Buildmaxheap and the second argument that calls the Max_heapify method in the Sort method. Why some from dataLength-1 began to decline, some have been passed 0, have thought, in fact, not difficult to answer, because in the beginning of the Buildmaxheap method must construct a maximum heap, at this time there is no assumptions about the data, the number is completely random, we can not guarantee a[0 ] Save the value is not the largest, if a[0] Save the value is the largest, then in the line and code 39-46, the largest variable forever value is 0, there is no result, so to start from the bottom of the comparison. However, when executing max_heapify in the Sort method, the arrangement of the data has the guarantee of the maximum heap nature. So you can start with 0, but it's absolutely no problem if you're going to compare it from the last.

Since the swap is over, it may result in a smaller value being exchanged, which is less than the value of its next face node, for example, in the last exchange in this example to 1, it should be like this when the exchange is complete:

  

All in order to ensure the nature of the maximum heap is recursive, this code is done by 47-51 lines.

Count Sort:

I personally like the count sort----simple, but there are some requirements for the data to be sorted, such as to know the range of the set of numbers to be sorted, the value of the input data should be in the open range of (0,k), and the data is preferably dense, if this group of data volatility is not suitable for sorting operations in the way of technical sorting. The central idea of a counting sort is that for a given value key to determine how many numbers are less than key, and how many values there are, then this value is the subscript of the key value that should be in the sorted array.

Direction to find a way to achieve, the key to counting sorting is how to calculate and save the number of values less than X value. The technical sort is saved by a temporary array, and the length of the array declaration is +1 of the length of the explicit maximum that we said earlier. For details on how to save, see the specific implementation:

1 package sort; 2  3/** 4  * Counting sort (prerequisites, the ability to know beforehand the upper limit of the desired sort, and the need for extra space) is suitable for data-intensive. There is a clear scope of the situation 5  *  6  * @author Think 7  *  8 *  /9 public class Countsort {Ten public     int[] sort (int[  ] data, int max_limit) {         int[] tmp = new int[max_limit];13         int[] des = new int[data.length];         = 0; i < data.length; i++) {             Tmp[data[i]] + = 1;16         }17 for         (int j = 1; j < Max_limit; J + +) {tmp[j             ] + = tmp[j-1];19
   }20 for         (int k = data.length-1; k >= 0; k--) {             des[tmp[data[k]]-1] = data[k];22             Tmp[data[k]]- = 1;23         }24         return des;26     }27 28}

12-13 rows, declaring a temporary array and the resulting array to be generated. The 14-16 line is the place where the counting sort is clever, the increment 1 is set on the data[i] coordinates of TMP, and the value of the subscript K in the TMP array is the number of k values in the data array. For example, in the data array there are 3 5 values, then the value saved in Tmp[5] is 3. For example, the array to be sorted is:

5 4 6 3 2 1

The contents of the TMP array after a 14-16-line cyclic operation are:

0 1 1 1 1 1 1

Based on the data in the TMP array, and the subscript of the TMP array, we can figure out the contents of the array to be sorted by 17-19 rows, and after 17-19 lines of processing, the contents of the TMP array are:

0 1 2 3 4 5 6

In combination with the subscript and value of TMP, it is known that the value of the subscript (Data[i]) of the TMP array is saved by 1, (tmp[data[i]]-1) is the position of the data[i] in the array where the data is sorted.

So the assignment is done in 20-23 rows and the sorting is complete. where 22 rows in tmp[data[k]]-= 1 is used to handle the case of duplicate values in the array that is being sought, and to sort the duplicates.

  

Bucket sort:

   If the values in the array to be sorted are evenly distributed, and in the interval [0,1], then the bucket ordering is a good choice, the bucket sort is to divide the [0,1] interval into 10 of the same size of the self-interval, and then the array of values properly "leaked" to the corresponding interval, such as 0.12 to be leaked to [ 0.1,0.2) is the value K to satisfy the left value of the interval <=k< the right value of the interval. Then in the way of inserting sort or quick sort to find out the values of each interval, here is the Bucket Finder code I implemented, which is a bit different from what the book says:

 1 package sort; 2 3 public class Bucketsort {4 5 public double[] Sort (double[] data) {6 return Bucket_sort (data); 7}  8 9 public double[] Bucket_sort (double[] data) {Ten double[] des = new double[data.length];11 bucket[]         TMP = new bucket[10];12 for (int i = 0; i < tmp.length; i++) {Tmp[i] = new Bucket (0, NULL); 14             }15 for (int i = 0; i < data.length; i++) {Bucket bucket = new Bucket (data[i], null); 17         int bucket_list_index = (int) (Data[i] * ten); Bucket_in_sort (Tmp[bucket_list_index], bucket); 19 }20 Int J = 0;21 for (int i = 0; i < tmp.length; i++) {Bucket tmp_bucket = tmp[i] . next;23 while (tmp_bucket! = null) {Des[j] = tmp_bucket.value;25 Tmp_bucke  t = tmp_bucket.next;26 j++;27}28}29 return des;30}31 public void Buckets_in_sort (bucket sourct_bucket, bucket bucket) {$ bucket TMP = SOURCT_BUCKET.NEXT;34 if (TMP = = null) {35             Sourct_bucket.next = bucket;36 return;37}38 while (tmp.next! = null) {39 if (Tmp.value > Bucket.value) {bucket.next = sourct_bucket.next;41 sourct_bucket . Next = bucket;42 break;43}44 tmp = tmp.next;45}46 tmp.next = bu cket;47}48-public class Bucket {Double value;51 public bucket next;52-public Buc         Ket (double value, bucket bucket) {this.value = value;55 This.next = bucket;56}57 58 Public double GetValue () {value;60 return}61, public void SetValue (double value) {         This.value = value;64}65, public Bucket getbucketlist () {next;68 return }69 PUBlic void Setbucketlist (Bucket next) {This.next = next;72}73 74}75 76} 

The bucket is an object I've defined to help me implement the bucket sort, with value and next two properties, value to hold the sorted value, next to represent the next object in the bucket, or null if it doesn't exist. 第12-14 row in each bucket to initialize a list object bucket, in the future along this link "leaky" in the value of the bucket, the 第15-18 line is to give each value to "leak" to that bucket, and then call the Bucket_in_sort method, in the "leak" such as the process of a bucket directly sorted, Drop the Bucket object with the value large to the back. 21-28th line is to take the value out of the bucket, and the value is the sort done.

  

A few common sorting algorithm is finished, different algorithms to solve the problem under different scenarios, welcome everyone and I exchange.

Here's the source code:

Http://files.cnblogs.com/fantiantian/Algorithm.rar

(RPM) 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.