8 Big sorting algorithms that Java programmers must master

Source: Internet
Author: User
Tags pow stub

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

Package Com.njue;  public class Insertsort {public  insertsort () {      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};      int temp=0;      for (int i=1;i<a.length;i++) {         int j=i-1;         Temp=a[i];         for (; j>=0&&temp<a[j];j--) {         a[j+1]=a[j];                       Move the value greater than temp to the overall back one unit         }         a[j+1]=temp;      for (int i=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 () {      int a[]={1,54,6,3,78,34,12,45,56,100};      Double d1=a.length;      int temp=0;      while (true) {          d1= Math.ceil (D1/2);          int d= (int) d1;          for (int x=0;x<d;x++) {for              (int i=x+d;i<a.length;i+=d) {                  int j=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 (int i=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 () {          int a[]={1,54,6,3,78,34,12,45};          int position=0;          for (int i=0;i<a.length;i++) {              int j=i+1;              position=i;              int temp=a[i];              for (; j<a.length;j++) {              if (a[j]<temp) {                  temp=a[j];                  position=j;              }              }              A[position]=a[i];              a[i]=temp;          }          for (int i=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>=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

Import Java.util.Arrays; public class Heapsort {int a[]={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 sort");          int arraylength=a.length;              Loop build heap for (int i=0;i<arraylength-1;i++) {//Jian Yu 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, int i, int j) {//TODO auto-generated method stub int tmp=          Data[i];          DATA[I]=DATA[J];      data[j]=tmp; }//to the data array from 0 to LastIndex build a large top heap private void Buildmaxheap (int[] data, int lastIndex) {//TODO Auto-generat The ed method stub//starts at the parent node of the LastIndex node (the last node) for (int i= (lastIndex-1)/2;i>=0;i--) {//k Saves the positive     In judging the node         int k=i; If the child node of the current K node exists while (K*2+1<=lastindex) {//k The index of the left child node of the node int biggerindex=2                  *k+1;                      If Biggerindex is less than lastIndex, 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 greater if (data[biggerindex]<data[biggerindex+1]) {//biggerindex always remember                      Record the index biggerindex++ of the larger child nodes;                      }}//If the value of the K-node is less than the value of its larger child node if (Data[k]<data[biggerindex]) {                      Swap them swap (DATA,K,BIGGERINDEX);                  The Biggerindex is given a K, starting the next loop of the while loop, and re-guaranteeing 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 () {       int a[]={ 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};      int temp=0;      for (int i=0;i<a.length-1;i++) {for          (int j=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 (int i=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) implemented in Java

public class QuickSort {int a[]={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 (int i=0;i<a.length;i++) System.out.println (A[i]);    } public int Getmiddle (int[] list, int. Low, int.) {int tmp = List[low]; The first of the array acts as a medium while (low < high) {while (Low < high && List[high] >=                     TMP) {high--;   } List[low] = List[high];                     A record smaller than the middle axis is moved to the low side while (lower < high && List[low] <= tmp) {low++;   } List[high] = List[low];              A record larger than the middle axis moved to the high end} List[low] = tmp;                   The middle axis is recorded to the tail return low;                   Returns the position of the middle axis} public void _quicksort (int[] list, int. Low, int.) {if (Low < high) { int middle = getmiddle (list, low, high);        Divides the list array into _quicksort (list, low, middle-1);       Recursive ordering of low-word tables _quicksort (list, middle + 1, high); Recursively sort the high-character table}} public void Quick (int[] A2) {if (A2.length > 0) {//             View 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

Import Java.util.Arrays; public class Mergingsort {int a[]={  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 (int i=0;i<a.length;i++) System.out.println (A[i]);          } public void sort (int[] data, int left, int right) {//TODO auto-generated Method stub if (left<right) {          Find Intermediate index int center= (left+right)/2;          Recursively sort (data,left,center) on the left array;          Recursively sort (data,center+1,right) on the right array;      Merging merge (Data,left,center,right);  }} public void merge (int[] data, int left, int center, int right) {//TODO auto-generated method stub int []      Tmparr=new Int[data.length];      int mid=center+1;      Third records the intermediate array's index int third=left;      int tmp=left;              while (left<=center&&mid<=right) {//Take the smallest drop from 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 sequentially 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

Import java.util.ArrayList;  Import java.util.List; public class Radixsort {int a[]={  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};      Public Radixsort () {sort (a);  for (int i=0;i<a.length;i++) System.out.println (A[i]);             } public void sort (int[] array) {//First determine the number of sorts of trips;             int max=array[0];                    for (int i=1;i<array.length;i++) {if (Array[i]>max) {max=array[i];                }} int time=0;                 Determine the number of digits;                     while (max>0) {max/=10;                 time++;                 }//Set up 10 queues;                 List<arraylist> queue=new arraylist<arraylist> ();                   for (int i=0;i<10;i++) {arraylist<integer> queue1=new arraylist<integer> ();             Queue.add (queue1); }//For time allocation and collection;                 for (int i=0;i<time;i++) {//allocation array element;                      for (int j=0;j<array.length;j++) {//Gets the number of time+1 digits;                     int x=array[j]% (int) Math.pow (ten, i+1)/(int) Math.pow (ten, I);                     Arraylist<integer> queue2=queue.get (x);                     Queue2.add (Array[j]);              Queue.set (x, queue2);                 } int count=0;//element counter;                     Collect queue elements;  for (int k=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.