Java implementation of sorting algorithm

Source: Internet
Author: User

1. Insert Sort

Principle: When traversing to the nth element, the N-1 element in front of it is already sorted, then find the previous N-1 element and put the nth element in the appropriate position, so that it goes through the elements of the sequence.
The complexity of the algorithm is also simple, the first order requires 1 of the complexity, sort the second requires 2 complexity, so the whole complexity is
1 + 2 + 3 + ... + n = O (n ^ 2) complexity.

Insert sort void insertsort (int array[], int length) {int I, j, key;        for (i = 1; i < length; i++) {key = array;  Move data that is greater than array before I for (j = i-1; J >= 0 && array[j] > key; j--) {array[j + 1]        = Array[j];    }//Place the current element in the appropriate position Array[j + 1] = key; }}

2.shell sorting

Principle: Divides the sequence into sub-sequences, then sorts the sub-sequences separately, and finally combines the subsequence. Each order divides the elements of a sequence into several sub-sequences according to an increment , inserts the sequence of these sequences, and then increments the number of elements of each subsequence by shrinking incrementally until the increment is one, and the subsequence is the same as the original order sequence. It is only necessary to do a small amount of comparison and movement to complete the sequencing of the sequence.

Shell sort void shellsort (int array[], int length) {int temp;  Increments start at half the length of the array, decreasing by one time for each (int increment = LENGTH/2; increment > 0;increment/= 2) for (int i = increment; i < length;            ++i) {temp = array; Inserts a set of increment elements into a sort for (int j = i; J >= increment; J-= increment) {// Before I move data that is greater than array backward if (temp < array[j-increment]) {Array[j] = array[                J-increment];                } else {break;        }}//Place the current element in the appropriate position array[j] = temp; }}

3. Bubble Sort

Principle: Each iteration of the sequence will be the largest (small) elements at the front, and then repeat the previous process for the remaining sequence, each time after the end of the sequence to be sorted less than one element, when the sort sequence is reduced to only one element when the order is finished. Therefore, the complexity in the worst case is O (N ^ 2) The bubble sort is stable and does not change the relative order of the same elements .

void Swap (int * A, int * b) {int temp;    temp = * A;    * a = * b;  * b = temp;}     Bubble sort void Bubblesort (int array[], int length) {//records whether there is an interchange of elements in a traversal, always comparing with adjacent elements, and moving forward with BOOL exchange;         for (int i = 0; i<length;++ i) {exchange= false; for (int j=i+1; j< length;++j) {if (Array[j] < array) {Exchan                Ge= true;            Swap (& Array[j], & Array);    }}//If this traversal does not have an exchange of elements, then the sort ends if (false = = Exchange) break; }}

4. Quick Sort

Principle: Select a PIVOT element, treat the sorting sequence to be divided, a part of the sequence after the division is less than the pivot element, a part is larger than the pivot element, and then the two well-divided sub-sequences of the above process.

Assuming that there are k nodes in the input array that are less than the axis value, then these nodes are placed in the leftmost k position of the array, and the greater than the axis is worth being placed in the n-k position at the far right of the array.

Selects a pivot element for a given range of sub-sequences, returns the location of the split element after executing the function,//The element before the split element is less than the pivot element, and the element behind it is greater than the element int Partition (int array[], int low, int    High) {//Use the first element of the subsequence as the pivot element int pivot = Array[low]; while (Low < high) {//from back to front in the second half to find the first element less than the pivot element while (Low < high && Array[high] >= PIV        OT) {--high;        }//Swap this element smaller than the pivot element to the first half swap (&array[low], &array[high]);        Look for the first element greater than the pivot element while in the first half of the trip (Low < high && Array[low] <= pivot) {++low;    }//Exchange this element larger than the pivot element to the second half swap (&array[low], &array[high]); }//Returns the location where the pivot element is located return low;} Quick sort void QuickSort (int array[], int low, int.) {if (Low < high) {int n = Partition (array, Low, hig        h);        QuickSort (array, low, n);    QuickSort (array, n + 1, high); }}

5. Merge Sort

Principle: Divide the sequence to be sorted into two parts of the same size, then merge and sort the two parts sequentially, and then combine them in sequence

Merging algorithms in merge sort void merge (int array[], int start, int mid, int end) {int temp1[10], temp2[10];    int N1, N2;    N1 = Mid-start + 1;    N2 = End-mid;    Copy the first half of the array for (int i = 0; i < N1; i++) {Temp1 = Array[start + i];    }//Copy the back half array for (int i = 0; i < n2; i++) {Temp2 = Array[mid + i + 1];    }//Put the latter element set to a very large temp1[n1] = temp2[n2] = 1000;        Scan the two fractional groups one by one and place them in the appropriate position for (int k = start, I = 0, j = 0; k <= end; k++) {if (Temp1 <= temp2[j])            {Array[k] = Temp1;        i++;            } else {array[k] = temp2[j];        j + +;        }}}//Merge sort void mergesort (int array[], int start, int end) {if (Start < end) {int i;        i = (end + start)/2;        Sort the first half of the MergeSort (array, start, I);        The second half is sorted mergesort (array, i + 1, end);    Merge two parts before and after merging (array, start, I, end); }}

6. Select Sort

Principle: Each trip selects the smallest (or largest) element from the data element to be sorted, placed in the final order of the ordered sequence, until all the data elements are sorted out. Select Sort is an unstable sort method.

The second is to select a small record in the array and place the record in the first position of the array.

Package Sort.select;import java.util.random;/**  * @author Liangge *  */public class Main {public static void Main ( String[] (args) {random ran = new Random (); int[] sort = new Int[10];for (int i = 0; i <; i++) {Sort[i] = Ran.nextint ( 50);} System.out.print ("Array before sorting is"); for (int i:sort) {System.out.print (i + "");} Selectsort (sort); System.out.println (); System.out.print ("sorted array is"); for (int i:sort) {System.out.print (i + "");}} /** * Select sort * @param sort */private static void Selectsort (int[] sort) {for (int i =0;i<sort.length-1;i++) {for (int j = i+1 ; j<sort.length;j++) {if (Sort[j]<sort[i]) {int temp = Sort[j];sort[j] = sort[i];sort[i] = temp;}}}}

7. Heap Sequencing

Definition of heap:

The N-keyword sequence kl,k2,...,kn is called a heap, when and only if the sequence satisfies the following properties (for short, heap properties):

(1) Ki≤k2i and Ki≤k2i+1 or (2) ki≥k2i and ki≥k2i+1 (1≤i≤)

If the vector stored in this sequence is R[1......N] as a storage structure of a complete binary tree, the heap is essentially a complete binary tree that satisfies the following properties: The keywords of any non-leaf nodes in the tree are not greater than (or not less than) the keywords of their left and right children (if any) nodes.

This nature of the heap makes it possible to quickly locate the smallest (large) element within a sequence.

The process of the heap sorting algorithm is as follows: 1) Gets the smallest (large) element of the current sequence 2) This element is exchanged with the last element so that the current smallest (large) element is placed at the end of the sequence, and the last element is placed at the very front of the sequence. 3) The exchange of the heap may break the nature of the sequence (note that at this time the sequence is to remove elements that have been placed on the last side), so the sequence needs to be adjusted to satisfy the nature of the heap above. Repeat the process until the sequence has been adjusted.

Array is the heap array to be adjusted, I is the position of the array element to be adjusted, length is the array of void heapadjust (int array[], int i, int nlength) {int nchild, ntemp;        for (ntemp = array; 2 * i + 1 < nlength; i = nchild) The position of the {//Sub-node is the parent node position * 2 + 1 nchild = 2 * i + 1; Get the larger nodes in the sub-nodes if (nchild! = nLength-1 && array[nchild + 1] > Array[nchild]) ++nchild        ;        If the larger child node is larger than the parent node, move the larger child node upward, replacing its parent node if (Ntemp < Array[nchild]) {array = Array[nchild];        } else//exit loop {break; }}//finally put the value of the element to be adjusted in the appropriate position array = ntemp;} Heap sorting algorithm void heapsort (int array[], int length) {//Adjusts the first half of the sequence of elements, after the adjustment of the element is the largest element of the sequence for (int i = LENGTH/2-1; I &G t;= 0;    -i) {heapadjust (array, I, length);        }//The sequence is adjusted from the last element, narrowing the adjustment until the first element for (int i = length-1; i > 0; i) {//swaps the first element and the current last element,        The element that guarantees the current last position is the largest Swap (&array[0], &array) in the present sequence; Keep shrinkingAdjust the range of the heap to ensure that the first element is the maximum value of the current sequence Heapadjust (array, 0, i); }}

  

Java implementation of 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.