First of all, I assume that this is more academic than practical, since you are not using the built-in sort function. However, here are some that help you move in the right direction:
: merge(), mergeSort(), . , .
:
merge(A, B):
C = empty list
While A and B are not empty:
If the first element of A is smaller than the first element of B:
Remove first element of A.
Add it to the end of C.
Otherwise:
Remove first element of B.
Add it to the end of C.
If A or B still contains elements, add them to the end of C.
mergeSort(A):
if length of A is 1:
return A
Split A into two lists, L and R.
Q = merge(mergeSort(L), mergeSort(R))
return Q
, , .
, MergeSort .
, .
public static void mergeSort(int[] array, int left, int lHigh, int right, int rHigh) {
int elements = (rHigh - lHigh +1) ;
int[] temp = new int[elements];
int num = left;
while ((left <= lHigh) && (right <= rHigh)){
if (a[left] <= a[right]) {
temp[pos] = a[left];
leftLow ++;
}
else {
temp[num] = a[right];
right ++;
}
num++;
}
while (left <= right){
temp[num] = a[left];
left += 1;
num += 1;
}
while (right <= rHigh) {
temp[num] = a[right];
right += 1;
num += 1;
}
for (int i=0; i < elements; i++){
a[rHigh] = temp[rHigh];
rHigh -= 1;
}
, . . , , :)
, . , , ( ). , O (N) O(N * log N), , , merge sort O(N^2).
:
- recursion mergeSort(). , . , for while, , .
, , , wikipedia, . , , , .
!
:
public static void mergeSort(int[] array, int left, int lHigh, int right, int rHigh) {
int elements = rHigh - left;
int[] temp = new int[elements];
int num = left;
int iL = left;
int iR = right;
while( temp is not full ) {
if( left side is all used up ) {
copy rest of right side in.
make sure that at the end of this temp is full so the
while loop quits.
}
else if ( right side is all used up) {
copy rest of left side in.
make sure that at the end of this temp is full so the
while loop quits.
}
else if (array[iL] < array[iR]) { ... }
else if (array[iL] >= array[iR]) { ... }
}
}