Алгоритм сортировки по сегменту

#c #algorithm #data-structures

#c #алгоритм #структуры данных

Вопрос:

Как я могу изменить код здесь, чтобы работать со значениями с плавающей запятой в массиве, когда я пытаюсь скомпилировать код, я получил сообщение об ошибке

итак, что мне здесь нужно, так это то, что мой код может работать со значениями с плавающей запятой, а не только с int, если я добавил массив со значениями int, он работает нормально, но со значениями с плавающей запятой выдает ошибку

Как я могу изменить код здесь, чтобы работать со значениями с плавающей запятой в массиве, когда я пытаюсь скомпилировать код, я получил сообщение об ошибке

итак, что мне здесь нужно, так это то, что мой код может работать со значениями с плавающей запятой, а не только с int, если я добавил массив со значениями int, он работает нормально, но со значениями с плавающей запятой выдает ошибку

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

#define NARRAY 100   // Array size
#define NBUCKET 100  // Number of buckets
#define INTERVAL 100  // Each bucket capacity

struct Node {
  int data;
  struct Node *next;
};

void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);

// Sorting function
void BucketSort(int arr[]) {
  int i, j;
  struct Node **buckets;

  // Create buckets and allocate memory size
  buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);

  // Initialize empty buckets
  for (i = 0; i < NBUCKET;   i) {
    buckets[i] = NULL;
  }

  // Fill the buckets with respective elements
  for (i = 0; i < NARRAY;   i) {
    struct Node *current;
    int pos = getBucketIndex(arr[i]);
    current = (struct Node *)malloc(sizeof(struct Node));
    current->data = arr[i];
    current->next = buckets[pos];
    buckets[pos] = current;
  }

  // Print the buckets along with their elements
  for (i = 0; i < NBUCKET; i  ) {
    printf("Bucket[%d]: ", i);
    printBuckets(buckets[i]);
    printf("n");
  }

  // Sort the elements of each bucket
  for (i = 0; i < NBUCKET;   i) {
    buckets[i] = InsertionSort(buckets[i]);
  }

  printf("-------------n");
  printf("Bucktets after sortingn");
  for (i = 0; i < NBUCKET; i  ) {
    printf("Bucket[%d]: ", i);
    printBuckets(buckets[i]);
    printf("n");
  }

  // Put sorted elements on arr
  for (j = 0, i = 0; i < NBUCKET;   i) {
    struct Node *node;
    node = buckets[i];
    while (node) {
      arr[j  ] = node->data;
      node = node->next;
    }
  }

  return;
}

// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list) {
  struct Node *k, *nodeList;
  if (list == 0 || list->next == 0) {
    return list;
  }

  nodeList = list;
  k = list->next;
  nodeList->next = 0;
  while (k != 0) {
    struct Node *ptr;
    if (nodeList->data > k->data) {
      struct Node *tmp;
      tmp = k;
      k = k->next;
      tmp->next = nodeList;
      nodeList = tmp;
      continue;
    }

    for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) {
      if (ptr->next->data > k->data)
        break;
    }

    if (ptr->next != 0) {
      struct Node *tmp;
      tmp = k;
      k = k->next;
      tmp->next = ptr->next;
      ptr->next = tmp;
      continue;
    } else {
      ptr->next = k;
      k = k->next;
      ptr->next->next = 0;
      continue;
    }
  }
  return nodeList;
}

int getBucketIndex(int value) {
  return value / INTERVAL;
}

void print(int ar[]) {
  int i;
  for (i = 0; i < NARRAY;   i) {
    printf("%d ", ar[i]);
  }
  printf("n");
}

// Print buckets
void printBuckets(struct Node *list) {
  struct Node *cur = list;
  while (cur) {
    printf("%d ", cur->data);
    cur = cur->next;
  }
}

// Driver code
int main(void) {
  int array[NARRAY] = {0.50, 100.00, 99.97, 51.20, 53.90, 28.10, 25.50, 66.40, 65.70, 0.00};

  printf("Initial array: ");
  print(array);
  printf("-------------n");

  BucketSort(array);
  printf("-------------n");
  printf("Sorted array: ");
  print(array);
  return 0;
}
 

Комментарии:

1. но со значениями с плавающей запятой это выдает мне ошибку , ну, какую ошибку? Кроме того, какой код с плавающими значениями выдает эту ошибку? (ii.e. Что вы изменили?) В main , вам нужно int array только инициализировать с помощью значений с плавающей запятой, таких как 0.50 . Итак, используется ли это рабочий код int ? Ваша [частичная] попытка использовать значения с плавающей запятой? Или гибрид этих двух? Пожалуйста, отредактируйте свой вопрос и добавьте эту дополнительную информацию.

2. Возможно, вам следует начать с фактического определения некоторых массивов типа float or double , а не просто записи чисел с плавающей запятой в int массив.

3. Пожалуйста, добавьте хотя бы вывод ошибки. И, если возможно, все отладочные данные, которые вы получили во время отладки.

Ответ №1:

Используйте этот код. Я создал свой собственный тип iORf данных . Используйте typedef int iORf и typedef float iORf для int и float соответственно. Для этого вам нужно переключиться вручную.

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

#define NARRAY 100   // Array size
#define NBUCKET 100  // Number of buckets
#define INTERVAL 100 // Each bucket capacity

typedef int iORf; //float or int, currently int

struct Node
{
    iORf data;
    struct Node *next;
};

void BucketSort(iORf arr[]);
struct Node *InsertionSort(struct Node *list);
void print(iORf arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(iORf value);

// Sorting function
void BucketSort(iORf arr[])
{
    int i, j;
    struct Node **buckets;

    // Create buckets and allocate memory size
    buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);

    // Initialize empty buckets
    for (i = 0; i < NBUCKET;   i)
    {
        buckets[i] = NULL;
    }

    // Fill the buckets with respective elements
    for (i = 0; i < NARRAY;   i)
    {
        struct Node *current;
        int pos = getBucketIndex(arr[i]);
        current = (struct Node *)malloc(sizeof(struct Node));
        current->data = arr[i];
        current->next = buckets[pos];
        buckets[pos] = current;
    }

    // Print the buckets along with their elements
    for (i = 0; i < NBUCKET; i  )
    {
        printf("Bucket[%d]: ", i);
        printBuckets(buckets[i]);
        printf("n");
    }

    // Sort the elements of each bucket
    for (i = 0; i < NBUCKET;   i)
    {
        buckets[i] = InsertionSort(buckets[i]);
    }

    printf("-------------n");
    printf("Bucktets after sortingn");
    for (i = 0; i < NBUCKET; i  )
    {
        printf("Bucket[%d]: ", i);
        printBuckets(buckets[i]);
        printf("n");
    }

    // Put sorted elements on arr
    for (j = 0, i = 0; i < NBUCKET;   i)
    {
        struct Node *node;
        node = buckets[i];
        while (node)
        {
            arr[j  ] = node->data;
            node = node->next;
        }
    }

    return;
}

// Function to sort the elements of each bucket
struct Node *InsertionSort(struct Node *list)
{
    struct Node *k, *nodeList;
    if (list == 0 || list->next == 0)
    {
        return list;
    }

    nodeList = list;
    k = list->next;
    nodeList->next = 0;
    while (k != 0)
    {
        struct Node *ptr;
        if (nodeList->data > k->data)
        {
            struct Node *tmp;
            tmp = k;
            k = k->next;
            tmp->next = nodeList;
            nodeList = tmp;
            continue;
        }

        for (ptr = nodeList; ptr->next != 0; ptr = ptr->next)
        {
            if (ptr->next->data > k->data)
                break;
        }

        if (ptr->next != 0)
        {
            struct Node *tmp;
            tmp = k;
            k = k->next;
            tmp->next = ptr->next;
            ptr->next = tmp;
            continue;
        }
        else
        {
            ptr->next = k;
            k = k->next;
            ptr->next->next = 0;
            continue;
        }
    }
    return nodeList;
}

int getBucketIndex(iORf value)
{
    return (int)value / INTERVAL;
}

void print(iORf ar[])
{
    int i;
    int flag = 0;
    iORf dummy = 1.5;
    if (dummy > 1)
        flag  ;
    for (i = 0; i < NARRAY;   i)
    {
        if (flag > 0)
            printf("%f ", ar[i]);
        else
            printf("%d ", ar[i]);
    }
    printf("n");
}

// Print buckets
void printBuckets(struct Node *list)
{
    struct Node *cur = list;
    while (cur)
    {
        printf("%d ", cur->data);
        cur = cur->next;
    }
}

// Driver code
int main(void)
{
    iORf array[NARRAY] = {0.5, 100.00, 99.97, 51.20, 53.90, 28.10, 25.50, 66.40, 65.70, 0.00};

    printf("Initial array: ");
    print(array);
    printf("-------------n");

    BucketSort(array);
    printf("-------------n");
    printf("Sorted array: ");
    print(array);
    return 0;
}