这段代码是一种简单的合并排序,可以通过划分和征服类比来实现。我得到一个未排序的数组作为输出,它与输入数组相同。请指出此代码中的错误:
import java.util.*;
class Merge {
public static void main(String[] args) {
int n,i;
Scanner sc = new Scanner(System.in);
System.out.println("enter size of array");
n = sc.nextInt();
int b[] = new int[n];
System.out.println("enter array");
for (i=0;i<n;i++) {
b[i] = sc.nextInt();
}
System.out.println("sorted array");
int c[] = sort(b);
for (i=0;i<n;i++) {
System.out.println(c[i]);
}
}
static int[] sort(int[] a) {
int i;
int l = a.length;
if (l<2) {
return a;
}
int mid = l/2;
int left[] = new int[mid];
int right[] = new int[l - mid];
for (i=0;i<mid;i++) {
left[i] = a[i];
}
for (i=mid;i<l;i++) {
right[i-mid] = a[i];
}
sort(left);
sort(right);
merge(left,right,a);
return a;
}
static void merge(int[] left , int[] right , int[] a) {
int p=0,q=0,r=0;
while (p<left.length && q<right.length) {
if (left[p]<=left[q]) {
a[r] = left[p];
p++;
} else {
a[r] = right[q];
q++;
}
r++;
}
while (p<left.length) {
a[r] = left[p];
p++;
r++;
}
while (q<right.length) {
a[r] = right[q];
q++;
r++;
}
}
}
答案 0 :(得分:1)
你的病情有问题
if (left[p]<=left[q]) {
应该是
if (left[p]<=right[q]) {