Import Java.util.Arrays;
public class Cao46
{
/**
* Merge Sort
*
* Three pointers: Two pointers are initially positioned at the beginning of the two sorted sequence, and the third pointer is in the middle of the two sequence
* Two methods: One is a recursive method
* One is a merge method, each trip will have a maximum of 2 n elements of the cell sort
* Working principle:
1, the application space, so that its size is the sum of two sorted sequences, the space used to store the combined sequence
2, set two pointers, the initial position is the starting position of two sorted series
3. Compare the elements pointed to by two pointers, select a relatively small element into the merge space, and move the pointer to the next position
4. Repeat step 3 until a pointer reaches the end of the sequence
5. Copy all remaining elements of another sequence directly to the end of the merge sequence
*/
public static void Main (string[] args)
{
Int[] array={1,6,3,2,5,9,4,7};
Sort (array,0,array.length-1);
System.out.println (arrays.tostring (array));//print array
}
public static void sort (int[] array, int left, int. right) {
if (left<right)
{
Find the intermediate index
int center= (left+right)/2;
Recursive to the left array
Sort (array,left,center);
Recursive to the right array
Sort (array,center+1,right);
Merge
Merge (Array,left,center,right);
}
}
public static void merge (int[] array, int. left, int mid, Int. right) {
int[] Temp = new Int[right-left + 1];
int L = left;//Left pointer
int r = Mid + 1;//right pointer
int k = 0;//Temporary array pointer
Move the smaller number first to the new array
while (l<= mid && R <= right)
{
if (Array[l] < array[r])
{
temp[k++] = array[l++];
}
Else
{
temp[k++] = array[r++];
}
}
Move the left remaining number into the array
while (L <= mid)
{
temp[k++] = array[l++];
}
Move the remaining number in the right side into the array
while (R <= right)
{
temp[k++] = array[r++];
}
Overwrites the number in the new array with an array of arrays
System.arraycopy (temp, 0, array, left, Right-left + 1);
}
}
Merge sort--java