【发布时间】:2014-09-14 13:44:02
【问题描述】:
我正在尝试编写一个程序来计算插入排序进行的交换次数。我的程序适用于小输入,但在大输入上会产生错误的答案。我也不确定如何使用long int 类型。
这个问题出现在https://drive.google.com/file/d/0BxOMrMV58jtmNF9EcUNQNGpreDQ/edit?usp=sharing描述的设置中
输入为
The first line contains the number of test cases T. T test cases follow.
The first line for each case contains N, the number of elements to be sorted.
The next line contains N integers a[1],a[2]...,a[N].
我使用的代码是
#include <stdio.h>
#include <stdlib.h>
int insertionSort(int ar_size,int * ar)
{
int i,j,t,temp,count;
count=0;
int n=ar_size;
for(i=0;i<n-1;i++)
{
j=i;
while(ar[j+1]<ar[j])
{
temp=ar[j+1];
ar[j+1]=ar[j];
ar[j]=temp;
j--;
count++;
}
}
return count;
}
int main()
{
int _ar_size,tc,i,_ar_i;
scanf("%d", &tc);
int sum=0;
for(i=0;i<tc;i++)
{
scanf("%d", &_ar_size);
int *_ar;
_ar=(int *)malloc(sizeof(int)*_ar_size);
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++)
{
scanf("%d", &_ar[_ar_i]);
}
sum=insertionSort(_ar_size, _ar);
printf("%d\n",sum);
}
return 0;
}
【问题讨论】:
-
你的 int 溢出了吗?
-
@GradyPlayer 是的,在第一种情况下,输入数量为 65911,在第三种情况下,输入 100,000 个。如果不使用 long,它会为小值提供正确的输出,当我使用 long int 时,它是也没有为小值提供正确的输出。例如:将输入作为 1 5 2 1 3 1 2 当我使用此代码时其输出为 4,当我使用 long 时其输出为 10
标签: c sorting insertion-sort