Java Classic Sorting algorithm

Source: Internet
Author: User

0 algorithm overview 0.1. Algorithm classification 10 kinds of common sorting algorithms can be divided into two major categories:

Sorting of nonlinear time comparison classes: The relative order between elements is determined by comparison, because its time complexity cannot break through O (Nlogn), so it is called nonlinear time comparison class ordering.

linear time Non-comparative class ordering: The relative order between elements is not determined by comparison, it can break through the lower bound of time based on the comparison sort and run in linear time, so it is called linear time non-comparative class sort.

0.2. Complexity of the algorithm

0.3. Related Concepts Stable: If A is originally in front of B, and A=b, then a is still in front of B.

not stable: If A is originally in front of B, and A=b, then a may appear behind B.

Complexity of Time: The total number of operations on the sorted data. Reflects the regularity of the number of operations when n changes.

Complexity of Space: Refers to the measurement of the storage space required by the algorithm when it executes within the computer, and it is also a function of the data size n. 1. Bubble sort (Bubble sort)
Bubble sort is a simple sort algorithm. It repeatedly visits the sequence to sort, compares two elements at a time, and swaps them if they are in the wrong 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.
The 1.1 algorithm description (1) compares adjacent elements. If the first one is larger than the second, swap them two, (2) do the same for each pair of adjacent elements, starting from the first pair to the end, so that the last element should be the largest number, and (3) Repeat the above steps for all elements except the last one; (4) Repeat steps 1~  3 until the sort is complete. 1.2 Code implementation
 Public classBubblesort { Public Static voidMain (string[] args) {intArr[] = {1,3,2,6,7,0,5};  for(inti=0; i<arr.length; i++){             for(intj=0; j<arr.length;j++){                if(arr[i]<Arr[j]) {                    intt =Arr[i]; Arr[i]=Arr[j]; ARR[J]=T; }            }        }         for(intA:arr)    System.out.print (a); }}

2. Select sort (Selection sort)
Select Sort (selection-sort) is a simple and intuitive sorting algorithm. It works by first finding the smallest (large) element in the unordered sequence, holding it to the starting position of the sort sequence, and then continuing to find the smallest (large) element from the remaining unsorted elements, and then dropping it to the end of the sorted sequence. And so on until all elements are sorted.
2.1 Algorithm Description
The direct selection of n records can be sorted by n-1 direct selection to get an ordered result. The specific algorithm is described as follows:

(1) The initial state: The disordered area is R[1..N], the ordered area is empty, and (2) when the first sequencing (I=1,2,3...N-1) is started, the current ordered and unordered areas are r[1..i-1] and R (I.) respectively.   N). The sequencing from the current unordered area-Select the smallest key record r[k], and the 1th record of the unordered zone R Exchange, so that r[1..i] and R[I+1..N) respectively to increase the number of records added to a new ordered area and the number of records decreased by 1 new unordered regions; (3) N-1 the end of the trip, the array is ordered. 2.2 Code implementation
 Public classSelectionsort { Public Static voidMain (string[] args) {intArr[] = {2,5,7,0,3,1,4,6};  for(inti=0; i<arr.length-1; i++){             for(intj=i+1; j<arr.length;j++){                                if(Arr[i] >Arr[j]) {                    intt =Arr[i]; Arr[i]=Arr[j]; ARR[J]=T; }            }        }         for(intA:arr)    System.out.print (a); }}
The 2.3 algorithm analyzes one of the most stable sorting algorithms, because no matter what data goes in is the time complexity of O (N2), so when it is used, the smaller the data size, the better. The only advantage might be that you don't take up extra memory space. In theory, choosing a sort might also be the most common sort of sorting method that people usually think of.
3. Insert sort (Insertion sort)
The algorithm description of Insert sort (insertion-sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it.
3.1 Algorithm Description
In general, the insertion sort is implemented using In-place on the array. The specific algorithm is described as follows:

(1) Starting from the first element, the element can be considered to have been sorted, (2) take the next element, and then scan from the back forward in the sequence of elements that have been ordered;
(3) If the element (sorted) is greater than the new element, move the element to the next position;
(4) Repeat step 3 until the sorted element is found to be less than or equal to the position of the new element;
(5) After inserting the new element into the position;
(6) Repeat step 2~5. 3.2 Code Implementation
 Public classInsertionsort { Public Static voidMain (string[] args) {int[] arr = {5,8,4,1,9,7,2,0,6,3};  for(inti=0;i<arr.length;i++){              for(intj=0;j<i;j++){                 if(arr[i]<Arr[j]) {                     inttemp =Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; }             }        }         for(intA:arr)    System.out.print (a); }}
3.3 Algorithm Analysis Insert sort on implementation, usually by in-place sort (i.e. only use O (1) of extra space to sort), so in the process of backward forward scanning, the ordered elements need to be moved back and forth gradually, to provide the most up-to-date elements insert space. The following is not yet sorted out.
4. Hill sort (Shell sort)
The 1959 Shell invention, the first breakthrough O (N2) sorting algorithm, is an improved version of the simple insert sort. It differs from the insertion sort in that it takes precedence over elements that are farther apart. Hill sort is also known as narrowing the incremental sort.
4.1 Algorithm Description
First, the entire sequence of records to be sorted into a number of sub-sequences for direct insertion of the sort, the specific algorithm description:

Select an incremental sequence T1,T2,...,TK, where ti>tj,tk=1;
According to the number of increment series K, the sequence is sorted by K-trip;
Each order, according to the corresponding increment ti, the backlog sequence is divided into several sub-sequences of length m, respectively, the sub-table is directly inserted sort.   Only the increment factor is 1 o'clock, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence. 4.3 Code implementation

function Shellsort (arr) {

var len = arr.length,

Temp

Gap = 1;

while (Gap < LEN/3) {//dynamic definition interval sequence

Gap = Gap * 3 + 1;

}

for (GAP; gap > 0; gap = Math.floor (GAP/3)) {

for (var i = gap; i < Len; i++) {

temp = Arr[i];

for (var j = i-gap; J > 0 && arr[j]> temp; j-=gap) {

Arr[j + gap] = arr[j];

}

Arr[j + gap] = temp;

}

}

return arr;

}

4.4 Algorithm Analysis

The core of the hill sort is the setting of the interval sequence. You can set the interval sequence in advance, or you can define the interval sequence dynamically.   The algorithm for dynamically defining the interval sequence is proposed by Robert Sedgewick, co-author of the algorithm (4th edition). 5, merge sorting (merge sort)
Merge sort is an efficient sorting algorithm based on the merging operation. This algorithm is a very typical application of the partition method (Divide and Conquer). The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If you combine two ordered tables into an ordered table, it is called a 2-way merge.

5.1 Algorithm Description

The input sequence of length n is divided into two sub-sequences of length n/2;
The two sub-sequences were sorted by merging;
Merges two sorted sub-sequences into a final sort sequence. 5.3 Code Implementation

function MergeSort (arr) {//uses a top-down recursive method

var len = arr.length;

if (Len < 2) {

return arr;

}

var middle = Math.floor (LEN/2),

left = Arr.slice (0, middle),

right = Arr.slice (middle);

Return merge (MergeSort (left), MergeSort (right));

}

function merge (left, right) {

var result = [];

while (left.length>0 && right.length>0) {

if (Left[0] <= right[0]) {

Result.push (Left.shift ());

} else {

Result.push (Right.shift ());

}

}

while (Left.length)

Result.push (Left.shift ());

while (Right.length)

Result.push (Right.shift ());

return result;

}

5.4 Algorithm Analysis

Merge sort is a stable sort method. As with select Sort, the performance of the merge sort is not affected by the input data, but behaves much better than the selection, since it is always the time complexity of O (Nlogn). The cost is that additional memory space is required.
6. Fast sorting (Quick sort)
The basic idea of quick sorting: to separate the pending records into two separate parts by a single pass, in which some of the recorded keywords are smaller than the other, the two parts of the record can be sorted separately to achieve the order of the whole sequence.

6.1 Algorithm Description

Quick sort use the divide-and-conquer method to divide a string (list) into two substrings (sub-lists). The specific algorithm is described as follows:

Select an element from the series, called the "Datum" (pivot);
Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, 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;
recursively (recursive) sorts sub-columns that are smaller than the base value elements and sub-columns that are larger than the base value elements. 6.3 Code Implementation

function QuickSort (arr, left, right) {

var len = arr.length,

Partitionindex,

left = typeof Left! = ' number '? 0:left,

right = typeof Right! = ' number '? Len-1: Right;

if (left < right) {

Partitionindex = partition (arr, left, right);

QuickSort (arr, left, partitionIndex-1);

QuickSort (arr, partitionindex+1, right);

}

return arr;

}

function partition (arr, left, right) {//partitioning operation

var pivot = left,//Set datum value (pivot)

index = pivot + 1;

for (var i = index, I <= right; i++) {

if (Arr[i] < Arr[pivot]) {

Swap (arr, I, index);

index++;

}

}

Swap (arr, pivot, index-1);

return index-1;

}

function swap (arr, I, j) {

var temp = arr[i];

Arr[i] = Arr[j];

ARR[J] = temp;

}
7. Heap sort (heap sort)
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.

7.1 Algorithm Description

The initial order-to-sort keyword sequence (r1,r2....rn) is constructed into a large top heap, which is the initial unordered area;
Swap the top element of the heap r[1] with the last element R[n] to get a new unordered area (R1,R2,...... RN-1) and the new ordered area (Rn), and satisfies the r[1,2...n-1]<=r[n];
Because the new heap top r[1] may violate the nature of the heap, it requires a current unordered zone (R1,R2,...... RN-1) adjusts to the new heap, then swaps the r[1] with the last element of the unordered zone, resulting in a new unordered area (r1,r2....rn-2) and a new ordered area (RN-1,RN).  This process is repeated until the number of elements in the ordered area is n-1, and the entire sorting process is complete. 7.3 Code Implementation

var Len; Because the data length is required for multiple functions declared, Len is set as a global variable

function Buildmaxheap (arr) {//Build large Top heap

len = arr.length;

for (var i = Math.floor (LEN/2), I >= 0; i--) {

Heapify (arr, i);

}

}

function Heapify (arr, i) {//Heap adjustment

var left = 2 * i + 1,

right = 2 * i + 2,

largest = i;

if (left < len && Arr[left] > Arr[largest]) {

largest = left;

}

if (right < Len && Arr[right] > Arr[largest]) {

largest = right;

}

if (Largest! = i) {

Swap (arr, I, largest);

Heapify (arr, largest);

}

}

function swap (arr, I, j) {

var temp = arr[i];

Arr[i] = Arr[j];

ARR[J] = temp;

}

function Heapsort (arr) {

Buildmaxheap (arr);

for (var i = arr.length-1; i > 0; i--) {

Swap (arr, 0, I);

len--;

Heapify (arr, 0);

}

return arr;

}
8. Sort by count (counting sort)
Counting sorting is not a sort algorithm based on comparison, the core of which is to convert the input data value into a key stored in an additional open array space. As a sort of linear time complexity, counting ordering requires that the input data be an integer with a definite range.

8.1 Algorithm Description

Find the largest and smallest elements in the array to be sorted;
The number of occurrences of each element in the statistic array that is I, in the array C;
Summation of all counts (starting with the first element in C, each item and the previous one);
Reverse-Populate the target array: Place each element I in the C (i) of the new array, minus 1 for each element that is placed. 8.3 Code implementation

function Countingsort (arr, maxValue) {

var bucket = new Array (MaxValue + 1),

Sortedindex = 0;

Arrlen = Arr.length,

Bucketlen = MaxValue + 1;

for (var i = 0; i < Arrlen; i++) {

if (!bucket[arr[i]]) {

Bucket[arr[i]] = 0;

}

bucket[arr[i]]++;

}

for (var j = 0; J < Bucketlen; J + +) {

while (Bucket[j] > 0) {

arr[sortedindex++] = j;

bucket[j]--;

}

}

return arr;

}

8.4 Algorithm Analysis

The Count sort is a stable sorting algorithm. When the input element is an integer of n 0 to K, the time complexity is O (n+k), and the spatial complexity is O (n+k), which is ordered faster than any comparison sorting algorithm. When k is not very large and the sequence is relatively concentrated, the count sort is a very efficient sorting algorithm.
9, bucket sort (bucket sort)
Bucket sorting is an upgraded version of the Count sort. It takes advantage of the mapping of functions, the key to efficiency is the determination of this mapping function. Bucket sort (bucket sort) works by principle: assuming that the input data is uniformly distributed, the data is divided into a limited number of buckets, and each bucket is sorted separately (it is possible to use a different sorting algorithm or recursively continue to use the bucket sort to arrange).

9.1 Algorithm Description

Set a quantitative array as an empty bucket;
Traverse the input data, and put the data into the corresponding bucket one by one;
Sort each bucket that is not empty;
From a bucket that is not empty, stitch up the sorted data. 9.3 Code Implementation

function Bucketsort (arr, bucketsize) {

if (arr.length = = = 0) {

return arr;

}

var i;

var minValue = arr[0];

var maxValue = arr[0];

for (i = 1; i < arr.length; i++) {

if (Arr[i] < MinValue) {

MinValue = Arr[i]; Minimum value of input data

} else if (Arr[i] > MaxValue) {

MaxValue = Arr[i]; Maximum value of input data

}

}

The initialization of buckets

var default_bucket_size = 5; Set the default number of buckets to 5

Bucketsize = Bucketsize | | Default_bucket_size;

var bucketcount = Math.floor ((maxvalue-minvalue)/bucketsize) + 1;

var buckets = new Array (bucketcount);

for (i = 0; i < buckets.length; i++) {

Buckets[i] = [];

}

Use mapping functions to assign data to individual buckets

for (i = 0; i < arr.length; i++) {

Buckets[math.floor ((Arr[i]-minValue)/bucketsize)].push (Arr[i]);

}

arr.length = 0;

for (i = 0; i < buckets.length; i++) {

Insertionsort (Buckets[i]); Sort each bucket, where the insert sort is used

for (var j = 0; J < Buckets[i].length; J + +) {

Arr.push (Buckets[i][j]);

}

}

return arr;

}

9.4 Algorithm Analysis

Bucket sorting is best used with linear time O (n), and the time complexity of bucket sequencing depends on the time complexity of sorting the data between buckets, because the time complexity of the other parts is O (n). Obviously, the smaller the bucket, the less data between buckets, and the less time it takes to sort. But the corresponding space consumption will increase.
10. Base sort (Radix sort)
The cardinality sort is sorted by low, then collected, sorted by high order, then collected, and so on, until the highest bit. Sometimes some properties are prioritized, sorted by low priority, and sorted by high priority. The final order is high priority high in front, high priority is the same low priority high in front.

10.1 Algorithm Description

Gets the maximum number in the array and obtains the number of digits;
Arr is the original array, starting from the lowest bit to take each bit to make up the radix array;
The radix is counted (using the count sort applies to the characteristics of the small range number); 10.3 Code Implementation

LSD Radix Sort

var counter = [];

function Radixsort (arr, maxdigit) {

var mod = 10;

var dev = 1;

for (var i = 0; i < maxdigit; i++, Dev *=, mod *= 10) {

for (var j = 0; J < Arr.length; J + +) {

var bucket = parseint ((arr[j]% mod)/dev);

if (counter[bucket]==null) {

Counter[bucket] = [];

}

Counter[bucket].push (Arr[j]);

}

var pos = 0;

for (var j = 0; J < Counter.length; J + +) {

var value = null;

if (counter[j]!=null) {

while ((value = Counter[j].shift ()) = null) {

arr[pos++] = value;

}

}

}

}

return arr;

}

10.4 Algorithm Analysis

The cardinality sort is based on sorting separately and is collected separately, so it is stable. However, the performance of the cardinality sort is slightly worse than the bucket ordering, and the time complexity of O (n) is required for each key's bucket allocation, and the time complexity of O (n) is required to get the new keyword sequence after allocation. If the data to be sorted can be divided into the D keyword, then the time complexity of the cardinality sorting will be O (d*2n), of course, D is much smaller than n, so it is basically linear level.

The spatial complexity of the cardinality sort is O (n+k), where K is the number of buckets. Generally n>>k, so the extra space needs about about N.

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