I am solving following problem on SPOJ.It is simple insertion sort algorithm. My java code works but C code is giving wrong answer. what wrong i am doing?
Please help and thanks lot......:)
java code
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 code
#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;
}
The code itself is correct, but your output is wrong. Expected output format is a number followed by newline. Your Java code uses println
which automatically inserts newline. Your C code lacks \n
. printf("%d\n", count);
is what you should use.