我尝试使合并排序从大到小,但它一直从小到大
I try to make the merge sort go from bigger to little but it keep going from little to big
试图从大变小我正在尝试使用排序和搜索合并排序:
import java.util.*;
class MergeSorter {
public static void sort(int[] a) {
if (a.length <= 1) { return; }
int[] first = new int[a.length / 2];
int[] second = new int[a.length - first.length];
for (int i = 0; i < first.length; i++) {
first[i] = a[i];
}
for (int i = 0; i < second.length; i++) {
second[i] = a[first.length + i];
}
sort(first);
sort(second);
merge(first, second, a);
}
private static void merge(int[] first, int[] second, int[] a) {
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
a[j] = first[iFirst];
iFirst++;
} else {
a[j] = second[iSecond];
iSecond++;
}
j++;
}
while (iFirst < first.length) {
a[j] = first[iFirst];
iFirst++; j++;
}
while (iSecond < second.length) {
a[j] = second[iSecond];
iSecond++; j++;
}
}
}
public class MergeSortDemo888888 {
public static void main(String[] args) {
int [] myAry = { 3, 2, 6, 7 };
System.out.println("myAry is " + Arrays.toString(myAry));
MergeSorter.sort(myAry);
System.out.println("myAry is sorted descendingly using selection sort: "+Arrays.toString(myAry));
}
}
在 merge
函数的第一个 if
中,只需将此 (first[iFirst] < second[iSecond])
更改为此 (first[iFirst] > second[iSecond])
。
试图从大变小我正在尝试使用排序和搜索合并排序:
import java.util.*;
class MergeSorter {
public static void sort(int[] a) {
if (a.length <= 1) { return; }
int[] first = new int[a.length / 2];
int[] second = new int[a.length - first.length];
for (int i = 0; i < first.length; i++) {
first[i] = a[i];
}
for (int i = 0; i < second.length; i++) {
second[i] = a[first.length + i];
}
sort(first);
sort(second);
merge(first, second, a);
}
private static void merge(int[] first, int[] second, int[] a) {
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
a[j] = first[iFirst];
iFirst++;
} else {
a[j] = second[iSecond];
iSecond++;
}
j++;
}
while (iFirst < first.length) {
a[j] = first[iFirst];
iFirst++; j++;
}
while (iSecond < second.length) {
a[j] = second[iSecond];
iSecond++; j++;
}
}
}
public class MergeSortDemo888888 {
public static void main(String[] args) {
int [] myAry = { 3, 2, 6, 7 };
System.out.println("myAry is " + Arrays.toString(myAry));
MergeSorter.sort(myAry);
System.out.println("myAry is sorted descendingly using selection sort: "+Arrays.toString(myAry));
}
}
在 merge
函数的第一个 if
中,只需将此 (first[iFirst] < second[iSecond])
更改为此 (first[iFirst] > second[iSecond])
。