Функция сортировки не будет печатать отсортированный массив? - PullRequest
0 голосов
/ 04 ноября 2018

Моя функция сортировки не будет печатать отсортированный массив?

Я пытаюсь написать программу, которая собирает элементы массива, сортирует массив, а затем печатает факториал каждого элемента. Я не хочу забегать вперед и писать рекурсивную функцию, если массив не сортируется правильно. Сортировка кажется мне хорошей; люди критиковали меня, используя цикл while, но я пока не знаю другого пути. Любой вклад приветствуется.

#include <stdio.h>

int sorter(int numbList[]);
int getData(int numList[]);
//int recursive(int numList[]);

int main(void) {
    int x;
    int numberList[x];

    getData(&numberList[x]);
    sorter(&numberList[x]);

    //recursive(&numberList[x]);
    return 0;
}

//gets user input-data
int getData(int numbList[]) {
    int i;
    int x;
    printf("Enter number of Elements:\n");
    scanf("%d", &x);

    printf("Enter the values for each element starting from first 
element:\n");

    for (i = 0; i < x; i++) {
        scanf("%d", &numbList[i]);
    }

    printf("\nYou have filled the array list with\n");
    for (i = 0; i < x; i++) {
        printf("%d\n", numbList[i]);
    }
    return numbList[x];
}

//sorter function
int sorter(int numbList[]) {
    int x;
    int temp;
    int swapped;

    while (1) {
        swapped = 0;
        for (int i = 0; i < x; i++) {
            if (i > numbList[i + 1]) {
                temp = numbList[x];
                numbList[x] = numbList[x + 1];
                numbList[x + 1] = numbList[x];
                swapped = 1;
            }
            if (swapped == 0) {
                break;
            }
        }
        printf("Array as sorted:\n");
        for (int i = 0; i < x; i++) {
            printf("%d\t", numbList[x]);
        }
        return(numbList[x]);
    }
}

//recursive factorial function
/* int recursive(int numbList[]) {
    int b = 0;
    numbList[b] *= numbList[b - 1];
    return 0;
} */

Ответы [ 3 ]

0 голосов
/ 04 ноября 2018

В вашем коде несколько проблем:

  • количество элементов x неинициализируется при определении массива numbList[x]. Это имеет неопределенное поведение. Вы должны передать указатель на счет в getData, и эта функция должна обновить это значение, выделить массив, прочитать значения и вернуть указатель на массив.

  • Вы не должны разбивать строки на несколько строк без \

  • Код подкачки не работает: тест if (i > numbList[i + 1]) неверен, он должен быть

    if (numbList[i] > numbList[i + 1])
    
  • код свопа должен использовать i вместо x в качестве индекса, а последнее назначение в коде свопа должно хранить temp в numbList[i + 1].
  • внутренний цикл должен остановиться на x - 1, чтобы избежать чтения за концом массива.
  • вы должны позволить внутреннему циклу работать до конца и выходить из внешнего цикла, если swapped == 0.

Вот исправленная версия:

#include <stdio.h>
#include <stdlib.h>

int *getData(int *count);
void sorter(int numList[], int count);

int main(void) {
    int x;
    int *numberList;

    numberList = getData(&x);
    if (numberList != NULL) {
        printf("Elements entered:");
        for (int i = 0; i < x; i++) {
            printf(" %d", numberList[i]);
        }
        printf("\n");
        sorter(numberList, x);
        printf("Sorted array:");
        for (int i = 0; i < x; i++) {
            printf(" %d", numberList[i]);
        }
        printf("\n");
        free(numberList);
    }
    return 0;
}

//gets user input-data
int *getData(int *countp) {
    int i, x;
    int *numbList;

    printf("Enter the number of elements: ");
    if (scanf("%d", &x) != 1 || x <= 0) {
        printf("Invalid size:");
        return NULL;
    }
    numbList = calloc(sizeof *numbList, x);
    if (numbList == NULL) {
        printf("Memory allocation error:");
        return NULL;
    }
    printf("Enter the element values: ");
    for (i = 0; i < x; i++) {
        if (scanf("%d", &numbList[i]) != 1) {
            free(numbList);
            return NULL;
        }
    }
    *countp = x;
    return numbList;
}

//sorter function

void sorter(int numbList[], int x) {
    for (;;) {
        int swapped = 0;
        for (int i = 0; i < x - 1; i++) {
            if (numbList[i] > numbList[i + 1]) {
                int temp = numbList[i];
                numbList[i] = numbList[i + 1];
                numbList[i + 1] = temp;
                swapped = 1;
            }
        }
        if (swapped == 0) {
            break;
        }
    }
}
0 голосов
/ 04 ноября 2018

Вы можете использовать технику алгоритма пузырьковой сортировки, которая является алгоритмом быстрой сортировки и использует цикл вместо цикла while

    int bubbleSorter(int numbList[])
{
    int temp;
    int i, x;

    bool swapped = false;
    for (i = 0; i < x - 1; i++)
    {
        swapped = false;
        for (j = 0; j < x - 1 - i; j++)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
                swapped = true;
            }
            else {
                swapped = false;
            }

        }

        // if no number was swapped that means 
        //   array is sorted now, break the loop. 
        if (!swapped) {
            break;
        }

        printf("Array as sorted:\n");

        for (int i = 0; i<x; i++)
        {
            printf("%d\t", numbList[x]);
        }
        return(numbList[x]);
    }

}
0 голосов
/ 04 ноября 2018

Некоторые подсказки в виде комментариев в вашем коде: Он все равно не справится с работой, но приведёт вас в лучшую форму ...

int main(void) 
{
  //uninitialized x!
  int x;
  //Even if you get a value for x, VLAs are depreciated
  int numberList[x];
  //Both calls get the adress of last value + 1 in numberList.
  //So you a) go out of the array bounds, and b) why would you want
  //the last element's address??
  //Just use it like getData(numberList);
  getData(&numberList[x]);
  sorter(&numberList[x]);
  return 0;
}

//gets user input-data
//What is the return value for?
int getData(int numbList[])
{
  int i;
  int x;
  printf("Enter number of Elements:\n");
  scanf("%d",&x);

  printf("Enter the values for each element starting from first element:\n");
  for(i=0;i<x;i++){
    scanf("%d",&numbList[i]);
  }

  printf("\nYou have filled the array list with\n");
  for(i=0;i<x;i++){
    printf("%d\n",numbList[i]);
  }
  //see above
  return numbList[x];
}

//sorter function
//Again, what and why return?
int sorter(int numbList[])
{
  //uninitialized x!
  int x;
  int temp;
  int swapped;

while(1)
{

 swapped=0;
 for(int i=0;i<x;i++)
 {
   //What do you compare here? Think.
   if(i>numbList[i+1])
   {
    temp=numbList[x];
    numbList[x]=numbList[x+1];
    //What do you have temp for??
    numbList[x+1]=numbList[x];
    swapped=1;
  }
  //Pretty sure you want an else clause here
  if(swapped==0)
  {
    break;
  }
}

  printf("Array as sorted:\n");
  for(int i=0;i<x;i++)
  {
     printf("%d\t",numbList[x]);
  }
  return(numbList[x]);
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...