Sorting algorithm (Java edition)

Source: Internet
Author: User

1. Bubbling algorithm
2. Quick Sort
3. Merge sort
4. Select sort
5. Heap Sequencing

Sorting algorithms

Importance is self-evident, many algorithm problems often choose a good sorting algorithm often problems can be solved

1. Bubble algorithm

Bubble sort (Bubble sort) is also a simple and intuitive sorting algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence. That's the problem with a double loop, but you need to be aware of the next frontier.

Algorithm steps:

1) compare adjacent elements. If the first one is bigger than the second one, swap them both.

2) 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.

3) Repeat the above steps for all elements except the last one.

4) Repeat the above steps each time for less and fewer elements until there is no pair of numbers to compare.

1  Public voidBubblesort (int[] a) {2     inttemp = 0;3     intLen =a.length;4      for(inti = 0; i < Len; i++) {5          for(intj = 1; J < Len-i; J + +)6             if(A[j-1] >A[j]) {7                 //Note whether a[j-1] or a[j] is prone to boundary problems8                 //sort from small to large9temp = A[j-1];TenA[J-1] =A[j]; OneA[J] =temp; A             } -     } -}

Optimized bubble sorting

Since it may have been sequenced in the first few times, it still needs to be traversed in the last bubble sort.

Optimization: Sets a flag that is true if the interchange occurred, otherwise false. Obviously if there was a trip without an exchange, the description sort has been completed.

1  Public voidBubbleSort1 (int[] a) {2     inttemp = 0;3     intLen =a.length;4     BooleanFlag =true;5      while(flag) {6Flag =false;7          for(intj = 1; J < Len-1; J + +)8             if(A[j-1] >A[j]) {9                 //Note whether a[j-1] or a[j] is prone to boundary problemsTen                 //sort from small to large Onetemp = A[j-1]; AA[J-1] =A[j]; -A[J] =temp; -                 //set Flag bit theFlag =true; -             } -     } -}

2. Quick Sort

Fast sequencing is a sort of algorithm developed by Donny Holl. On average, sort n items to 0 (n log n) comparisons. In the worst case scenario, a 0 (N2) comparison is required, but this is not a common situation. In fact, fast sequencing is usually much faster than the other 0 (n log n) algorithms because its internal loop (inner Loop) can be implemented efficiently on most architectures.

Quick sort uses the divide-and-conquer (Divide and conquer) strategy to divide a serial (list) into two sub-serial (sub-lists).

Algorithm steps:

1) Pick an element from the sequence called "Datum" (pivot)

2) Reorder the series, where all elements are placed in front of the datum at a smaller value than the datum, and all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation.

3) recursively (recursive) sorts sub-columns that are less than the base value element and sub-columns that are larger than the base value element.
At the bottom of the recursive scenario, the size of the sequence is 0 or one, which is always sorted. Although it is always recursive, the algorithm always exits, because in each iteration (iteration), it will at least put an element to its last position.

1 Private Static voidQuick_sort (int[] arr,intLowintHigh ) {2     //Resolve and Merge3     if(Low <=High ) {4         intMID =partition (arr, low, high);5         //Recursive6Quick_sort (arr, Low, mid-1);7Quick_sort (arr, mid + 1, high);8     }9 Ten } One  A Private Static intPartitionint[] arr,intLowintHigh ) { -     //decomposition -     intPivot =Arr[high]; the     inti = Low-1; -     inttemp; -      for(intj = Low; J < High; J + +) { -  +         if(Arr[j] <pivot) { -i++; +temp =Arr[i]; AArr[i] =Arr[j]; atARR[J] =temp; -         } -     } -     //exchanging intermediate elements and Privot -temp = arr[i + 1]; -Arr[i + 1] =Arr[high]; inArr[high] =temp; -     returni + 1; to  +}

3. Merge sort

Merge sort is an efficient sorting algorithm based on merging operations. This algorithm is a very typical application of the partition method (Divide and Conquer).

Algorithm steps:

1. Apply the space so that it is the sum of two sorted sequences that are used to store the merged sequence

2. Set two pointers, the initial position is the starting position of two sorted series

3. Compare the elements pointed to by two pointers, select a relatively small element into the merge space, and move the pointer to the next position

4. Repeat step 3 until a pointer reaches the end of the sequence

5. Copy all remaining elements of another sequence directly to the end of the merge sequence

1  Public Static int[] Sort (int[] Nums,intLowintHigh ) {  2     intMid = (low + high)/2; 3     if(Low <High ) {  4         //left5 sort (nums, low, mid); 6         //Right7Sort (Nums, Mid + 1, high); 8         //merge right and left9 merge (Nums, Low, Mid, high); Ten     }   One     returnNums;  A }   -  -  Public Static voidMergeint[] Nums,intLowintMidintHigh ) {   the     int[] temp =New int[High-Low + 1];  -     inti = low;//left Pointer -     intj = mid + 1;//Right Pointer -     intK = 0;  +  -     //move the smaller number first to the new array +      while(I <= mid && J <=High ) {   A         if(Nums[i] <Nums[j]) {   attemp[k++] = nums[i++];  -}Else {   -temp[k++] = nums[j++];  -         }   -     }   -  in     //Move the left remaining number into the array -      while(I <=mid) { totemp[k++] = nums[i++];  +     }   -  the     //move the remaining number in the right side into the array *      while(J <=High ) {   $temp[k++] = nums[j++]; Panax Notoginseng     }   -  the     //overwrites the number in the new array with the Nums array +      for(intK2 = 0; K2 < Temp.length; k2++) {   ANUMS[K2 + Low] =TEMP[K2];  the     }   +}

4. Select sort

Select sort (Selection sort) is also a simple and intuitive sorting algorithm.

Algorithm steps:

1) First find the smallest (large) element in the unordered sequence, and place it in the starting position of the sort sequence

2) continue to find the smallest (large) element from the remaining unsorted elements, and then place it at the end of the sorted sequence.

3) Repeat the second step until all the elements are sorted.

1  Public int[] Chosesort (int[] intarr) {  2      for(inti=0;i<intarr.length;i++){  3         intLowindex =i; 4 5          for(intj=i+1;j<intarr.length;j++){  6             if(intarr[j]<Intarr[lowindex]) {  7Lowindex =J; 8             }  9         }  Ten  One         //swaps the current first element with the smallest element in the sequence that follows it, that is, placing the smallest element in the front-end A         inttemp =Intarr[i];  -Intarr[i] =Intarr[lowindex];  -Intarr[lowindex] =temp;  the     }   -  -     returnintarr;  -}

5. Heap Sequencing

Heap ordering (heapsort) refers to a sort algorithm designed using the data structure of the heap. A heap is a structure that approximates a complete binary tree and satisfies the properties of the heap at the same time: that is, the key value or index of the child node is always less than (or greater than) its parent node.
The average time complexity for heap sorting is 0 (NLOGN).

Algorithm steps:

1) Create a heap h[0..n-1]

2) Swap the stack head (maximum) with the end of the heap

3) Reduce the size of the heap by 1 and call Shift_down (0) to adjust the new array top data to the corresponding position

4) Repeat step 2 until the size of the heap is 1

Tuning the heap section is not very good to write recommendations for reference http://blog.csdn.net/jdream314/article/details/6634863
Finally, a performance comparison chart of each algorithm is given.

Reference: http://www.cricode.com/3212.html

http://blog.csdn.net/morewindows/article/details/7961256

Sorting algorithm (Java edition)

Related Article

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.