我想检查数组是否以C或desc顺序在C中排序。
这是使用mpicc -Wall -o文件file.c进行编译的结果,因为我稍后在代码中使用MPI库。
mypractice1.c: In function ‘isSorted’:
mypractice1.c:38:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
/usr/bin/ld: unrecognised emulation mode: ypractice1
Supported emulations: elf_x86_64 elf32_x86_64 elf_i386 elf_iamcu i386linux elf_l1om elf_k1om i386pep i386pe
collect2: error: ld returned 1 exit status
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
//Function to check the order
int isSorted(int size, int array[]) {
if(size<=1)
return 1; //is ordered
int i;
for(i = 1; i < size; i++){
if(array[i] >= array[i-1])
return 1; //is Sorted ascending
else if (array[i]< array[i-1])
return 2; //is sorted descending
else return 0; //is not ordered
}
}
如何解决此错误?
最佳答案
您说您有:
// Function to check the order
int isSorted(int size, int array[])
{
if (size <= 1)
return 1; // is ordered
for (int i = 1; i < size; i++)
{
if (array[i] >= array[i - 1])
return 1; // is Sorted ascending
else if (array[i] < array[i - 1])
return 2; // is sorted descending
else
return 0; // is not ordered
}
}
您不能只检查前两个值就返回。您可能应该定义是否希望数据按升序或降序排序,并验证是否已得到数据,但是如果您真的想分析数据的顺序,则可以使用:
// Function to check the order
// 0 all equal
// 1 non-decreasing (ascending)
// 2 non-increasing (descending)
// -1 inconsistent (some ascending, some descending)
int isSorted(int size, int array[])
{
if (size <= 1)
return 1; // is ordered; deemed ascending
int num_eq = 0; // Number of adjacent pairs that are equal
int num_lt = 0; // Number of adjacent pairs sorted ascending
int num_gt = 0; // Number of adjacent pairs sorted descending
for (int i = 1; i < size; i++)
{
if (array[i] > array[i - 1])
num_gt++; // is sorted ascending
else if (array[i] < array[i - 1])
num_lt++; // is sorted descending
else
num_eq++; // is not ordered
}
assert(num_gt + num_lt + num_eq == size - 1);
if (num_gt == size - 1)
return 1; // ascending with all unique
if (num_lt == size - 1)
return 2; // descending with all unique
if (num_eq == size - 1)
return 0; // all rows equal
if (num_gt != 0 && num_lt != 0)
return -1; // inconsistent sorting
if (num_gt + num_eq == size - 1)
return 1; // ascending with some equal
if (num_lt + num_eq == size - 1)
return 2; // descending with some equal
return -1; // can't happen?
}
还有其他方法可以执行此操作,但是用尾注进行解释非常简单。在函数的尾部使用
else if
链将是可行且明确的。它有一些优点。您可以编码更多的返回值,以区分严格递增和非递减,还是严格递减或非递增。关于c - 控制到达C中非无效函数的结尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50317621/