简体   繁体   English

C 程序没有返回任何东西

[英]C Program isn't returning anything

I wrote a C program to sort an array, but the program isn't returning anything -- it just runs and stuck there as if it is waiting for input.我编写了一个 C 程序来对数组进行排序,但该程序没有返回任何内容——它只是运行并卡在那里,就好像它在等待输入一样。 Below is the code:下面是代码:

#include<stdio.h>

bool unsorted(int ar[],int x){
    int c;
    for(int i=1;i<=x;i++){
        if(ar[0]>ar[i]){
            return true;
        } else {
            return false;
        }
    }
}   

void sort(int arr[],int s){
    int h,b;
    while(unsorted(arr,s)){
        h=arr[0];
        for(int i=0;i<=s;i++){
            if(arr[i]>h){
                b=arr[i];
                arr[i]=h;
                h=b;
            }
        }
     }
     for(int i=0;i<=s;i++){
       printf("%d",arr[i]);
    }
}
int main(){
    int arr[3]={ 2,1,3 };
    sort(arr,3);
    return 0;
}

Your function unsorted returns true if the first element ist not the smallest.如果第一个元素不是最小的,则您的函数unsorted返回true It is not checked whether any other 2 elements are in wrong order.不检查任何其他 2 个元素的顺序是否错误。 This will cause wrong results but is not the reason for current problem.这将导致错误的结果,但不是当前问题的原因。

In your sorting loop you check if any element is larger than the first and then swaps them.在您的排序循环中,您检查是否有任何元素大于第一个元素,然后交换它们。 This means ascending order is changed to descending.这意味着升序更改为降序。 This will cause unsorted function to return true all the time and your loop never terminates.这将导致unsorted函数始终返回true并且您的循环永远不会终止。

To fix it change condition:要修复它,请更改条件:

void sort(int arr[],int s) {
    int h,b;
    while (unsorted(arr,s)) {
        h=arr[0];
        for (int i = 1; i < s; i++) {
            if (h > arr[i]) {
                b = arr[i];
                arr[i] = h;
                h = b;
            }
        }
    }
    for (int i=0; i < s; i++) {
            printf("%d",arr[i]);
    }
}

Also the index range was fixed.此外,索引范围是固定的。

This should at least make your loop terminate.这至少应该使您的循环终止。 It will not produce a sorted list as you terminate too early.由于您过早终止,它不会生成排序列表。

First of all your unsorted function needs some update:首先,您的unsorted函数需要一些更新:

bool unsorted(int ar[], int x) {
    int c;
    for (int i = 1; i < x; i++) {
        if (ar[i-1] > ar[i]) {
            return true;
        }
    }
    return false;
}   

This should also return true if first element is lowest but others don't fit like {1, 4, 3, 6} .如果第一个元素最低但其他元素不适合{1, 4, 3, 6}这也应该返回true Also note the fixed index range.还要注意固定索引范围。

You need to apply a similar fix to the sorting part to handle out-of-order values in the elements after the first one.您需要对排序部分应用类似的修复程序,以处理第一个元素之后的元素中的乱序值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM