简体   繁体   中英

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. 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. It is not checked whether any other 2 elements are in wrong order. 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.

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:

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} . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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