8 Big sorting algorithms that Java programmers must master

Source: Internet
Author: User

The relationship between the 8 kinds of sorting:


1, direct Insert sort

(1) Basic idea: In the set of numbers to be sorted, assume that the number of front (n-1) [n>=2] is already a row

In a good order, now you want to insert the nth number into the ordinal number in front, so that the n number

It's also in the right order. This cycle is repeated until all the rows are in order.

(2) Example


(3) Implementation in Java

Packagecom.njue;

public class Insertsort {

Publicinsertsort () {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};

Inttemp=0;

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

Intj=i-1;

Temp=a[i];

for (; j>=0&&temp<a[j];j--) {

A[J+1]=A[J]; Move the value greater than temp to one unit after the whole

}

A[j+1]=temp;

}

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

}
2, Hill Sort (minimum incremental sort)

(1) Basic idea: The algorithm will sort the group of numbers according to an increment D (n/2,n to the number of orders to be sorted) into groups, each group of records of the subscript difference D. Direct insert sorting of all elements in each group, followed by a smaller increment (D/2) to group it, The direct insert sort is then done in each group. When the increment is reduced to 1 o'clock, the sort is completed after the direct insert sort.

(2) Example:


(3) Implementation in Java

public class Shellsort {

Public Shellsort () {

INTA[]={1,54,6,3,78,34,12,45,56,100};

Doubled1=a.length;

Inttemp=0;

while (true) {

d1= Math.ceil (D1/2);

intd= (int) D1;

for (intx=0;x<d;x++) {

for (Inti=x+d;i<a.length;i+=d) {

intj=i-d;

Temp=a[i];

for (; j>=0&&temp<a[j];j-=d) {

A[J+D]=A[J];

}

A[j+d]=temp;

}

}

if (d==1)

Break

}

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

}
3. Simple selection of sorting

(1) Basic idea: In the group of numbers to be sorted, choose the smallest one and the number of the first position to exchange;

Then in the remaining number, find the smallest and second position of the number of exchanges, so loop to the penultimate number and the last number comparison.

(2) Example:


(3) Implementation in Java

public class Selectsort {

Public Selectsort () {

INTA[]={1,54,6,3,78,34,12,45};

intposition=0;

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

intj=i+1;

Position=i;

Inttemp=a[i];

for (; j<a.length;j++) {

if (a[j]<temp) {

TEMP=A[J];

Position=j;

}

}

A[position]=a[i];

A[i]=temp;

}

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

}
4, Heap sort

(1) Basic idea: heap sorting is a sort of tree selection, which is an effective improvement to the direct selection sort.

The heap is defined as follows: A sequence with n elements (h1,h2,..., HN) is called a heap when and only if it satisfies (hi>=h2i,hi& gt;=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2). Only the heap that satisfies the former condition is discussed here. As can be seen from the definition of a heap, the top element of the heap (that is, the first element) must be the largest (large top heap). A fully binary tree can represent the structure of a heap visually. Heap top is the root, the other is Zuozi, right subtree. The sequence of the numbers to be sorted is initially treated as a two-fork tree that is stored sequentially, adjusting their storage order to become a heap, when the heap has the largest number of root nodes. The root node is then exchanged with the last node of the heap. The number of fronts (n-1) is then re-adjusted to make it a heap. And so on, until there are only two nodes of the heap, and exchange them, and finally get an ordered sequence of n nodes. In terms of algorithm description, heap sequencing requires two processes, one is to build the heap, and the other is the last element of the heap to exchange the position. So the heap sort has two functions. One is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sorting.

(2) Example:

Initial sequence: 46,79,56,38,40,84

Build heap:


Swap, kicking the maximum number out of the heap

And so on: The last two remaining nodes in the heap are exchanged, kicked out, and sorted.

(3) Implementation in Java

Importjava.util.Arrays;

Publicclass Heapsort {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};

Public Heapsort () {

Heapsort (a);

}

public void Heapsort (int[] a) {

System.out.println ("Start sorting");

Intarraylength=a.length;

Loop Build Heap

for (inti=0;i<arraylength-1;i++) {

Build a heap

Buildmaxheap (a,arraylength-1-i);

Swap heap top and last element

Swap (a,0,arraylength-1-i);

System.out.println (Arrays.tostring (a));

}

}

private void Swap (int[] data, Inti, INTJ) {

TODO auto-generated Method Stub

Inttmp=data[i];

DATA[I]=DATA[J];

data[j]=tmp;

}

Build a large top heap from 0 to lastindex for the data array

private void Buildmaxheap (int[] data, Intlastindex) {

TODO auto-generated Method Stub

Starting at the parent node of the lastindex node (the last node)

For (inti= (lastIndex-1)/2;i>=0;i--) {

K Save the node being judged

Intk=i;

If the child node of the current K-node exists

while (K*2+1<=lastindex) {

Index of the left child node of the K-node

intbiggerindex=2*k+1;

If Biggerindex is less than lastindex, that is, the right child node of the K node represented by biggerindex+1 exists

if (Biggerindex<lastindex) {

If the value of the right child node is large

if (Data[biggerindex]<data[biggerindex+1]) {

Biggerindex always records the index of a larger child node

biggerindex++;

}

}

If the value of the K-node is less than the value of its larger child nodes

if (Data[k]<data[biggerindex]) {

Exchange them

Swap (Data,k,biggerindex);

Assign the Biggerindex to K, start the next loop of the while loop, and re-guarantee that the value of the K-node is greater than the value of its left and right child nodes

K=biggerindex;

}else{

Break

}

}

}

}

}
5. Bubble sort

(1) The basic idea: in order to sort a group of numbers, the current is not yet ranked in the range of all the number, from top to bottom of the adjacent two numbers in turn to compare and adjust, so that the larger number to sink, smaller upward. That is, each time a comparison of two adjacent numbers finds that they are in the opposite order of order, they are interchanged.

(2) Example:


(3) Implementation in Java


public class Bubblesort {

Public Bubblesort () {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};

Inttemp=0;

for (inti=0;i<a.length-1;i++) {

for (intj=0;j<a.length-1-i;j++) {

if (A[j]>a[j+1]) {

TEMP=A[J];

A[J]=A[J+1];

A[j+1]=temp;

}

}

}

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

}
6. Quick Sort

(1) Basic idea: Select a datum element, usually select the first element or the last element, through a scan, the waiting sequence is divided into two parts, some smaller than the Datum element, part is greater than the datum element, when the datum element in its correct position after the order, Then the same method is used recursively to sort the two parts of the division.

(2) Example:


(3) Implementation in Java

public class QuickSort {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};

Public QuickSort () {

Quick (a);

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

public int getmiddle (int[] list, Intlow, Inthigh) {

Inttmp = List[low]; The first of the arrays as a middle axis

while (Low < high) {

while (Low < high && List[high] >= tmp) {

high--;

}

List[low] = List[high]; Less than mid-axis records moved to the low end

while (Low < high && List[low] <= tmp) {

low++;

}

List[high] = List[low]; A record larger than the middle axis moves to the high end

}

List[low] = tmp; Middle axis record to tail

Returnlow; Returns the position of the middle axis

}

public void _quicksort (int[] list, Intlow, Inthigh) {

if (Low < high) {

Intmiddle = Getmiddle (list, low, high); Divides a list array into a split

_quicksort (list, low, middle-1); Recursive ordering of low-word tables

_quicksort (list, middle + 1, high); Recursive ordering of high-character tables

}

}

public void Quick (int[] A2) {

if (A2.length > 0) {//See if the array is empty

_quicksort (A2, 0, A2.length-1);

}

}

}
7. Merge sort

(1) Basic sorting: Merge (merge) sorting method is to combine two (or more than two) ordered tables into a new ordered table, that is, to sort the sequence into a number of sub-sequences, each sub-sequence is ordered. Then the ordered subsequence is combined into a whole ordered sequence.

(2) Example:


(3) Implementation in Java

Importjava.util.Arrays;

public class Mergingsort {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};

Public Mergingsort () {

Sort (a,0,a.length-1);

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

public void sort (int[] data, intleft, Intright) {

TODO auto-generated Method Stub

if (left<right) {

Find the intermediate index

Intcenter= (Left+right)/2;

Recursive to the left array

Sort (data,left,center);

Recursive to the right array

Sort (data,center+1,right);

Merge

Merge (Data,left,center,right);

}

}

public void merge (int[] data, intleft, Intcenter, intright) {

TODO auto-generated Method Stub

Int[] tmparr=newint[data.length];

intmid=center+1;

Third records the index of an intermediate array

Intthird=left;

Inttmp=left;

while (Left<=center&&mid<=right) {

Take the smallest of the two arrays into the middle array

if (Data[left]<=data[mid]) {

Tmparr[third++]=data[left++];

}else{

Tmparr[third++]=data[mid++];

}

}

The remainder is placed in the middle array in turn

while (Mid<=right) {

Tmparr[third++]=data[mid++];

}

while (Left<=center) {

Tmparr[third++]=data[left++];

}

Copy the contents of the intermediate array back to the original array

while (Tmp<=right) {

Data[tmp]=tmparr[tmp++];

}

System.out.println (arrays.tostring (data));

}

}
8. Base Order

(1) The basic idea: to unify all the values to be compared (positive integers) to the same digit length, the number of the short number of the first complement 0. Then, start with the lowest bit and order one at a time. Thus, from the lowest bit to the highest order, the sequence becomes an ordered series.

(2) Example:


(3) Implementation in Java

Importjava.util.ArrayList;

Importjava.util.List;

public class Radixsort {

INTA[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51};

Publicradixsort () {

Sort (a);

for (inti=0;i<a.length;i++)

System.out.println (A[i]);

}

public void sort (int[] array) {

First, the number of sorts is determined;

INTMAX=ARRAY[0];

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

if (Array[i]>max) {

Max=array[i];

}

}

inttime=0;

Determine the number of digits;

while (max>0) {

max/=10;

time++;

}

Set up 10 queues;

List<arraylist> queue=newarraylist<arraylist> ();

for (inti=0;i<10;i++) {

Arraylist<integer> queue1=newarraylist<integer> ();

Queue.add (queue1);

}

Time allocation and collection;

for (inti=0;i<time;i++) {

assigning array elements;

for (intj=0;j<array.length;j++) {

Get the number of time+1 digits;

intx=array[j]% (int) Math.pow (ten, i+1)/(int) Math.pow (n, i);

Arraylist<integer> queue2=queue.get (x);

Queue2.add (Array[j]);

Queue.set (x, queue2);

}

intcount=0;//element counter;

Collect queue elements;

for (intk=0;k<10;k++) {

while (Queue.get (k). Size () >0) {

Arraylist<integer> Queue3=queue.get (k);

Array[count]=queue3.get (0);

Queue3.remove (0);

count++;

}

}

}

}

}

8 Big sorting algorithms that Java programmers must master

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.