Summary of eight major sorts of Java

Source: Internet
Author: User

1. Direct Insert Sort:

How to Write code:

First set the number of inserts, that is, the number of cycles, for (int i=1;i<length;i++), 1 number of the time without inserting.

Sets the number of inserts and the number of digits that are the last number of the sequence that has been ranked. Insertnum and J=i-1.

Loops forward from the last number, and moves the current number one bit backwards if the number of insertions is less than the current number.

Places the current number in an empty position, that is, j+1.

The code is implemented as follows:

public class Insertsort {

public static void Insertsort (int[] a) {
int length = A.length; The length is removed to increase the speed
int insertnum;
for (int i=1;i<length;i++) {//number of times to insert
Insertnum = A[i];
int j = i-1;
while (J>=0&&insertnum<a[j]) {
A[J+1] = A[j];
j--;
}
For example, 3 6 5, when J is found at 3, insert 5 in the j+1 position.
A[j+1]=insertnum;
}
}

public static void Main (string[] args) {
Int[] a= {3,6,5};
Insertsort (a);
System.out.println (Arrays.tostring (a));
}
}

2. Hill Sort:

public class Sheelsort {

public static void Sheelsort (int[] a) {
int d = a.length;
while (d!=0) {
D = D/2;
for (int x = 0; x < D; × x + +) {//Number of groups
for (int i=x+d; i<a.length; i=i+d) {//elements in a group, starting with 2nd
int j = i-d; J is the number of digits in the last digit of the ordered sequence
int temp = A[i]; The element to insert
for (; j>=0&&temp<a[j]; j=j-d) {
A[j+d] = a[j];//move backwards D-bit
}
A[J+D] = temp;
}

}
}
}

public static void Main (string[] args) {
Int[] a ={592,401,874,141,348,72,911,887,820,283};
Sheelsort (a);
System.out.println (Arrays.tostring (a));
}
}

3. simple selection of sorting

public class Selectsort {

public static void Selectsort (int[] a) {
int len = a.length;
int minindex,temp;
for (int i=0;i<len-1;i++) {
Minindex = i;
for (int j=i+1;j<len;j++) {
if (A[j]<a[minindex]) {
Minindex = j;
}
}
temp = A[i];
A[i] = A[minindex];
A[minindex] = temp;
}
}

public static void Main (string[] args) {
Int[] a ={592,401,874,141,348,72,911,887,820,283};
Selectsort (a);
System.out.println (Arrays.tostring (a));
}

}

4. Heap Sequencing

The optimization of simple selection sorting.

Build the sequence into a large top heap.

Swaps the root node with the last node, and then disconnects the last node.

Repeat the first to second step until all the nodes are disconnected.

Heap sorting key to understand, from the bottom up, adjust the node, for example, the tree altogether 3 layers, then the 2nd layer of the tree as the root node, to ensure that its sub-nodes are smaller than it, at this time, if the 1th layer is adjusted, if the left node is the maximum value, will be the first layer of the root node and the left To ensure that the 1th tier satisfies the structure of the maximum heap, it is possible to break the maximum heap structure of the left node of the 1th layer, so the heap of the left node of this 1th layer needs to be re-adjusted. -------------This is the key to understand!

public class Heapsort {

Public Heapsort () {

}

public static void Heapsort (int[] a) {
System.out.println ("Start sorting");
int arraylength=a.length;
Loop Build Heap
for (int i=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);
}
}



private static void Swap (int[] data, int i, int j) {
TODO auto-generated Method Stub
int tmp=data[i];
DATA[I]=DATA[J];
data[j]=tmp;
}

Build a large top heap from 0 to lastindex for the data array
private static void Buildmaxheap (int[] data, int lastIndex) {
Starting at the parent node of the lastindex node (the last node)

for (int i= (lastIndex-1)/2;i>=0;i--) {
K Save the node being judged
int k=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
int biggerindex=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
If you do not understand, then use the break point of the way to run, you can find that when i=0, because node 1 and node 0 exchange, so need to readjust the 1-node heap structure, to ensure that
The value of the 1 node is still greater than the value of its left and right nodes
K=biggerindex;
}else{
Break
}
}
}
}

public static void Main (string[] args) {
int a[] = {7,13,6,43,5,23,4};
Heapsort (a);
System.out.println (Arrays.tostring (a));
}
}

5. Bubble Sort

Compares all elements in a sequence to 22, placing the largest in the last face.

Compares all elements in the remaining series to 22, placing the largest in the last face.

Repeat the second step until there is only one number left.

How to Write code:

Sets the number of cycles.

Sets the number of bits to start comparing, and the number of bits to end.

22 Compare, put the smallest to the front.

Repeat steps 2 and 3 until the number of loops is complete.

public class Bubblesort {

public static void Bubblesort (int[] a) {
Boolean issorted = true;
for (int i=0;i<a.length-1&&issorted;i++) {
issorted = false;
for (int j=0;j<a.length-1-i;j++) {
if (A[j]>a[j+1]) {
int temp = A[j];
A[J] = a[j+1];
A[J+1] = temp;
issorted = true;//Inner Loop If an interchange occurs, the proof continues to sort
}
}
If the order is completed after 1 trips, then the 2nd trip ends, issorted = false; At this time
The outer loop can end prematurely based on the issorted status of the tag.
}
}
public static void Main (string[] args) {
Int[] a ={592,401,874,141,348,72,911,887,820,283};
Bubblesort (a);
System.out.println (Arrays.tostring (a));
}
}

6. Quick Sort

public class QuickSort {

/**
* Find out the middle axis (the default is the lowest bit low) in the numbers array after sorting the location
*
* @param numbers with find array
* @param low start position
* @param high end position
* @return the location of the axis
*/
public static int Getmiddle (int[] numbers, int. Low,int High)
{
int temp = Numbers[low]; The first of the arrays as a middle axis
while (Low < high)
{
while (Low < high && Numbers[high] > Temp)
{
high--;
}
Numbers[low] = numbers[high];//smaller than the middle axis to move to the low end
while (Low < high && Numbers[low] < temp)
{
low++;
}
Numbers[high] = Numbers[low]; A record larger than the middle axis moves to the high end
}
Numbers[low] = temp; Middle axis record to tail
return low; Returns the position of the middle axis
}

/**
*
* @param numbers with sorted array
* @param low start position
* @param high end position
*/
public static void QuickSort (int[] numbers,int low,int High)
{
if (Low < high)
{
int middle = getmiddle (Numbers,low,high); Divides a numbers array into a split
QuickSort (Numbers, low, middle-1); Recursive ordering of low-field tables
QuickSort (Numbers, middle+1, high); Recursively sort a high-field table
}

}

/**
* Quick Sort
* @param numbers with sorted array
*/
public static void Quick (int[] numbers)
{
if (Numbers.length > 0)//See if the array is empty
{
QuickSort (Numbers, 0, numbers.length-1);
}
}

public static void Main (string[] args) {
int a[] = {6,7,8,5,3,12};
Quick (a);
System.out.println (Arrays.tostring (a));
}
}

7. Merge Sort

public class MergeSort {
/**
* Merge Sort
* Introduction: Merging two (or more than two) ordered tables into a new ordered table divides the ordered sequence into several sub-sequences, each of which is ordered. And then merge the ordered subsequence into the whole ordered sequence.
* Time complexity of O (NLOGN)
* Stable Sorting method
* @param nums array to be sorted
* @return Output ordered array
*/
public static 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;
}

public static void Merge (int[] nums, int. =, 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];
}
}


Implementation of merge sort
public static void Main (string[] args) {

Int[] Nums = {2, 7, 8, 3, 1, 6, 9, 0, 5, 4};

Mergesort.sort (nums, 0, nums.length-1);
System.out.println (arrays.tostring (nums));
}
}

8. Base Sorting

/*
* for an int array, write a cardinal sort algorithm that sorts the elements of the arrays.

Given an int array A and the size of the array n, return the sorted array. The guaranteed element is less than or equal to 2000.

Test examples:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
*/
public class Radissort {
Everyone, the method of installation
public static int[] Radixsort (int[] A, int n) {
First, the number of sorts is determined;
int max=a[0];
for (int i=1;i<n;i++) {
if (A[i]>max) {
Max=a[i];
}
}
int time=0;
Determine the number of digits;
while (max>0) {
max/=10;
time++;
}
int length = n;
int divisor = 1;//defines the divisor of each round, 1,10,100 ...
int[][] Bucket = new int[10][length];//defines 10 buckets in case each one is all in one bucket
Int[] Count = new int[10];//counts the number of elements actually stored in each bucket
int digit;//Gets the number on the corresponding bit in the element, which is loaded into the bucket
for (int i = 1; I <= time; i++) {//4 pass-through operation, sorting complete
for (int temp:a) {//Calculate into bucket
digit = (temp/divisor)% 10;
bucket[digit][count[digit]++] = temp;
}
int k = 0;//the subscript of the sorted array
for (int b = 0; b < b++) {//from 0 to 9th buckets are taken in sequence
if (count[b] = = 0)//If no elements in this bucket are put in, then skip
Continue
for (int w = 0; w < count[b]; w++) {
a[k++] = bucket[b][w];
}
COUNT[B] = 0;//The elements in the bucket have all been removed and the counter is zeroed
}
Divisor *= 10;
}
return A;
}

public static void Main (string[] args) {
int a[] = {1,2,3,5,2,3};
System.out.println (Arrays.tostring (Radixsort (A, a.length));
}
}

8 Sorting algorithm Analysis:

Complexity of Time:

Complexity of space:

Stability:

Summarize.

Summary of eight major sorts of Java

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.