Common sorting algorithm - merge sort (b)

Merging Algorithm

Correct what the illustration yesterday,

Finally there is a place, it should be said that the sub-array is divided to the last moment when (ie a sub-array has only one number) is not ordered [in fact, is certainly one small or equal between the two numbers, the logic It is ordered, but the direction is not the same size Bale],

When merge sub-array is the order that will take .

 

 

 

Well, just because of yesterday's talk of a merger idea, so I want two sub-arrays of arrays in good order. Today's code is not the same! !

The most important merge algorithm divide and conquer idea came today. .

 

 

 

Man of few words! ! The Code!

// merge algorithm
/ *
merge algorithm is most important is the recursive call, (ie: the method itself calls itself)
to write a simple recursive call pseudo-code:
public static void main (String args []) {
System.out. Printin (F (10));
}

static Long F (n-int) {
IF (n-<. 1) return -1;
IF (n-==. 1). 1 return;

return n-F + (. 1-n-); // recursive call the method itself.
}

Merge sort of thought is this: If a disordered array, then this array into two,
if the array into two or disorder, then continue down the score group, points out the array until ordered
(typically, the array is divided only two numbers, the two numbers must ordered)

* /
Package SDX;

public class Main10 {

static void main public (String [] args) {
// the proviso that two sub-arrays have a good order
int a [] = {56,78,789,3,890,66,73,547,67,8,54,7546,23} ;
Sort (A, 0,. 1-a.length);

Print (A);
}
// partition thought
static void Sort (A int [], int left, int right) {
IF (left == right) {
return;
}
IF (left> right) {
System.out.println ( "your input is what a few stuff?");
return;
}
// System.out.println (left);
// System.out.println ( right);
// Get an intermediate value divided in half ,,
int + mID = left (right-left) / 2;
// Sort the left
sort (a, left, mid) ;
sorting // the right
sort (a, mid + 1, right);

Merge (A, left, + MID. 1, right);

}
// merge thought
static void Merge (A int [], int leftPtr, rightPtr int, int rightBound) {
// array is disconnected from intermediate
int. 1-MID = rightPtr;
// allocate auxiliary space
int temp [] = new int [rightBound - leftPtr + 1] ;

// i = 0 means a position of a first half of the previous array
// j = min + 1 refers to the first position after the upper half of the array. 3
// K = 0 refers to the first position in the temp

int i = leftPtr, j = rightPtr, k = 0;

while (i <= mid && j <= rightBound) {

temp[k++] = a[i] <= a[j] ? a[i++] : a[j++];// 就一句话

}
while (i <= mid)
temp[k++] = a[i++];
while (j <=rightBound)
temp[k++] = a[j++];
for(int m=0;m<temp.length;m++){
a[leftPtr+m]=temp[m];
}
}

static void print(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

Guess you like

Origin www.cnblogs.com/sdx-BK/p/12070130.html