Java implementation of seven sorting algorithms

Source: Internet
Author: User

/**
* 1. Insert sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* The basic idea of inserting a sort is that, in the process of traversing an array, it is assumed that the element that precedes the ordinal I, [0..i-1], is already sorted,
* This tour needs to find the correct position k for element x corresponding to I, and to move the compared elements one after another in the process of looking for this position K.
* for element X "vacated position", and finally the value of K corresponding element is assigned to X
*
* In general, the time complexity and spatial complexity of insertion sequencing are O (n2) and O (1) respectively
*/

Public int[] Sortinsert (int[] array) {
for (int i=1;i<array.length;i++) {
int temp = Array[i];
Int J;
for (j=i-1;j >= 0 && temp< array[j]; j--) {
Array[j + 1] = Array[j];
}
Array[j + 1] = temp;
}
return array;
}

/**
* 2. Select the sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* The basic idea of selecting a sort is to iterate over the array, to represent the sequence number that is currently ordered, and to find the minimum value in the remaining [i...n-1].
* Then the found minimum value is exchanged with the value I points to. Because each pass determines the element's process there will be a selection of the maximum value of the sub-process, so people are visually referred to as the choice of sorting.
* Sorting time complexity and space complexity are O (N2) and O (1) respectively
*/

Public int[] Sortselect (int[] arr) {
for (int i = 0; i < arr.length; i++) {
int minipost = i;
for (int m = i + 1; m < arr.length; m++) {
if (Arr[m] < Arr[minipost]) {
Minipost = m;
}
}

if (Arr[i] > Arr[minipost]) {
int temp;
temp = Arr[i];
Arr[i] = Arr[minipost];
Arr[minipost] = temp;
}
}
return arr;
}

/**
* 3. Bubble sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* Bubble sort is to sink the bigger numbers to the bottom and the smaller ones to float on top
*
*/
Public int[] Sortbubble (int[] array) {
int temp;
First loop: Indicates the number of comparisons, such as the length of the element, the number of comparisons is length-1 times (certainly does not need to compare with oneself)
for (int i=0;i<array.length-1;i++) {
for (int j = array.length-1; j > i; j--) {
if (Array[j] < array[j-1]) {
temp = Array[j];
ARRAY[J] = array[j-1];
ARRAY[J-1] = temp;
}
}
}
return array;
}

/**
* 4. Fast sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
* Split the pending records into separate two parts by a single pass, with some of the recorded keywords smaller than the other part of the keyword,
* You can continue to sort the two parts of the record, which has reached the order of the whole sequence.
* The essence is, find a base (pivot, watershed, the role of the left is smaller than it, the right is bigger than it.) random, named base
* First from the right of the sequence to find smaller than base, if small, change position, so that base moved to the right (compared to the base smaller) position (recorded as a temporary high), so that the base on the right is larger than base
* Then, starting from the far left of the sequence, look for a larger one than base
*, if large, change position so that base moves to the left (compared to base) position (recorded as a temporary low bit), so that base on the left is smaller than base
* Cycle above two steps until the low = = Heigh, which makes it true to find the pivot, watershed. Return to this position, the left and right sequences of the watershed, and then recursively
*
*/

Public int[] Sortquick (int[] array) {
return QuickSort (array, 0, array.length-1);
}

Private int[] QuickSort (int[] arr, int low, int heigh) {
if (Low < Heigh) {
int division = partition (arr, low, heigh);
QuickSort (arr, Low, division-1);
QuickSort (ARR, Division + 1, Heigh);
}
return arr;
}

The watershed, the base, the left is smaller than the position, and the right side is big.
private int partition (int[] arr, int low, int heigh) {
int base = Arr[low]; Pivot (watershed) record with the first record of a child table
while (Low < Heigh) {//alternate from both ends of the table to the intermediate scan
while (Low < Heigh && Arr[heigh] >= base) {
heigh--;
}
Base is assigned to the current Heigh bit, base moved (swapped) to here, Heigh bit to the right of the larger than base
Swap (arr, heigh, Low);
while (Low < Heigh && Arr[low] <= base) {
low++;
}
The left side is larger than the base value, change position
Swap (arr, heigh, Low);
}
Now low = Heigh;
return low;
}

private void Swap (int[] arr, int a, int b) {
int temp;
temp = Arr[a];
Arr[a] = arr[b];
ARR[B] = temp;
}

/**
* 5. Merge sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* Merge sort takes the recursive implementation, which belongs to "divide and conquer", divides the target array from the middle, then sorts the two arrays separately.
* After sorting, the two arrays of the sorted sequence are "merged" together, and the most important one is the "merge" process.
* The merging process requires an additional amount of space consistent with the number of two numbers that need to be merged.
*/
Private int[] Sort (int[] nums, int low, int.) {
int mid = (low + high)/2;
if (Low < high) {
Left
Sort (nums, low, mid);
Right
Sort (Nums, mid + 1, high);
Merge Right and Left
Merge (Nums, Low, Mid, high);
}
return nums;
}


private void Merge (int[] nums, int low, int mid, Int. high) {
int[] Temp = new Int[high-low + 1];
int i = low;//left pointer
Int J = mid + 1;//right pointer
int k = 0;
Move the smaller number first to the new array
while (I <= mid && J <= High) {
if (Nums[i] < nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
}
}
Move the left remaining number into the array
while (I <= mid) {
temp[k++] = nums[i++];
}
Move the remaining number in the right side into the array
while (J <= High) {
temp[k++] = nums[j++];
}
Overwrites the number in the new array with the Nums array
for (int k2 = 0; K2 < temp.length; k2++) {
NUMS[K2 + Low] = Temp[k2];
}
}


Public int[] Sortmerge (int[] array) {
Return sort (array, 0, array.length-1);
}

/**
* 6. Hill Sort algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* The birth of the hill sort is due to the fact that the insertion sort will encounter the problem of moving too many elements when dealing with large arrays. The idea of hill sort is to divide a large array of
* Divided into several small arrays, divided by gap, such as array [1, 2, 3, 4, 5, 6, 7, 8], if divided by gap = Second,
* Can be divided into [1, 3, 5, 7] and [2, 4, 6, 8] two arrays (corresponding, such as Gap = 3,
* The array is divided into: [1, 4, 7], [2, 5, 8], [3, 6] and then the divided array is inserted to sort,
* After each sub-array is sorted and then reduce the gap value repeat the previous steps until Gap = 1, that is, the entire array is inserted sort,
* At this point the array is almost ready to be sequenced, so the elements that need to be moved are small and small, solving the problem of inserting sort in handling large arrays with more movement times.
*
* Hill sort is an improved version of the insertion sort, which helps to improve the efficiency when the data volume is large, and it is advisable to use the insertion sort directly when the data volume is small.
*/
Public int[] Sortshell (int[] array) {
Take increment
int step = ARRAY.LENGTH/2;
while (step >= 1) {
for (int i = step; i < Array.Length; i++) {
int temp = Array[i];
int j = 0;
And the difference between the insertion sort is right here.
for (j = i-step; J >= 0 && temp < array[j]; J-= Step) {
Array[j + Step] = Array[j];
}
Array[j + step] = temp;
}
Step/= 2;
}
return array;
}

/**
* 7. Heap sorting algorithm
* @paramInt[] Array not sorted
* @return Int[] Rank the ordinal group
*
* The essence is to first construct a big top heap, the parent is bigger than children, the root node is the largest node
* Swap the maximum node (root) with the tail node (the last node, smaller) position
* The last end of the tail node, now the largest, the rest, starting from the first element to the front of the tail node, construct a large top heap recursion
*
*/
Public int[] SortHeap (int[] array) {
Buildheap (array);//Build Heap
int n = array.length;
int i = 0;
for (i = n-1; I >= 1; i--) {
Swap (array, 0, i);
Heapify (array, 0, i);
}

return array;
}


private void Buildheap (int[] array) {
int n = number of elements in the array.length;//array
for (int i = N/2-1; I >= 0; i--)
Heapify (Array, I, n);
}


private void Heapify (int[] A, int idx, int max) {
int left = 2 * idx + 1;//(if present) the child's subscript
int right = 2 * idx + 2;//left child's subscript (if present)
int largest = 0;//looking for the subscript of the maximum node in 3 nodes
if (left < Max && A[left] > A[idx])
largest = left;
Else
largest = IDX;
if (Right < Max && A[right] > A[largest])
largest = right;
if (Largest! = IDX) {
Swap (A, largest, IDX);
Heapify (A, largest, max);
}
}




Build the heap function, think that only s in "S,m"
The corresponding keyword does not meet the definition of large top heap, and by adjusting the "s,m" becomes the Big Top heap =====================================================
public static void Heapadjust (int[] array, int s, int m) {
Using 0 subscript elements as the staging unit
Array[0] = Array[s];
Filter downward along the child's larger node
for (int j = 2 * s; j <= m; J *= 2) {
Ensure J is subscript for larger child nodes, J < m guarantee J+1 <= m, non-crossed
if (J < m && Array[j] < Array[j + 1]) {
j + +;
}
if (! ( Array[0] < Array[j])) {
Break
}
If the s bit is small, move the larger child up
Array[s] = Array[j];
The value of the older child becomes the smaller of the s bit, which may cause the top heap to be unbalanced, so the heap in which it resides is filtered
s = j;
}
If the s bit is large, the value is the same; otherwise, the s bit moves down to 2*s, 4*s 、。。。
Array[s] = array[0];
}

Java implementation of seven sorting algorithms

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.