You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

链表数组实现桶排序的节点插入问题排查求助

桶排序程序排错:节点插入问题导致排序失败

我编写了一个通过桶排序(Bin Sort)对数值数组进行排序的程序,按照桶排序的实现方式创建了链表数组。但程序无法正常完成排序,推测问题出在节点插入环节——节点未与头节点正确建立连接。以下是我的实现代码及对应的算法示意图:

// Bucket or Bin sort 
#include<iostream>
using namespace std;

//Bin sort has linear complexity( O(n))

// node class
class node
{
public:
  int data;
  node *next;
};

// print array function
void
print (int arr[], int n)
{
  for (int i = 0; i < n; i++)
    {
      cout << arr[i] << " ";
    }
  cout << endl;
}

// max element of array function
int
get_max (int arr[], int n)
{
  int max = arr[0];

  for (int i = 0; i < n; i++)
    {
      if (arr[i] > max)
    max = arr[i];
    }

  return max;
}

// insert function of linked list at end needs head pointer
void
insert (node * head, int x)
{
  node *temp = new node;
  temp->data = x;
  temp->next = nullptr;

  while (head)
    {
      head = head->next;
    }
  head = temp;
}


void
Bin_sort (int arr[], int n)
{

  // max element of array
  int max_num = get_max (arr, n);
  int i;

  // double node pointer act as array of pointer of heads of linked lists
  node **bin;
  bin = new node *[max_num + 1];

  // pointing each head as nullptr
  for (i = 0; i < max_num + 1; i++)
    {
      bin[i] = nullptr;
    }

  // inserting value of array at position in linked list array
  for (i = 0; i < n; i++)
    {
      insert (bin[arr[i]], arr[i]);
    }


  // after filling linked lists array retrieving data to fill back in main array (arr) in sorted manner
  int k = 0;
  for (i = 0; i < max_num + 1; i++)
    {
      while (bin[i] != nullptr)
    {
      arr[k] = bin[i]->data;
      cout << arr[k] << endl;
      bin[i] = bin[i]->next;
      k++;
    }
    }

}


int
main ()
{
  int arr[] = { 3, 22, 34, 12, 15, 22 };
  print (arr, 6);
  Bin_sort (arr, 6);
  cout << "after sortion" << endl;
  print (arr, 6);
  return 7;
}

桶排序算法示意图

内容的提问来源于stack exchange,提问作者Divyansh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:10:18