我正在解决以下SPOJ问题。它是简单的插入排序算法。我的java代码工作,但C代码给出了错误的答案。 我在做什么错?C代码给出了错误的答案,但java代码给出了正确的答案spoj
请帮助和感谢很多...... :)
Java代码
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t > 0) {
int n = Integer.parseInt(br.readLine());
String str = br.readLine();
String arr[] = str.split(" ");
int inputArr[] = new int[n];
for (int i = 0; i < n; i++) {
inputArr[i] = Integer.parseInt(arr[i]);
}
int key = 0;
int count = 0;
for(int i = 1; i < n; i++) {
key = inputArr[i];
int j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
count++;
}
inputArr[j + 1] = key;
}
System.out.println(count);
t--;
}
}
}
C代码
#include<stdio.h>
int main() {
int t=0;
scanf("%d",&t);
while(t > 0) {
int n=0;
scanf("%d",&n);
int arr[n];
int key=0;
for(int i=0; i<n; i++) {
scanf("%d",&arr[i]);
}
int count=0;
int j=0;
for(int i=1; i<n; i++) {
key = arr[i];
j = i - 1;
while(j>=0&&arr[j]>key) {
arr[j+1]=arr[j];
count++;
j = j-1;
}
arr[j+1]=key;
}
printf("%d",count);
t--;
}
return 0;
}
有什么不对?什么是对的?你的输入是什么?已经完成的输出是什么?你真正看到了什么? –
在插入排序中执行交换操作的次数 –
您的Java代码使用'println'来添加换行符,但是您的C代码在输出'printf'中没有'\ n'。 – aragaer