首页 \ 问答 \ 按多个参数对链表进行排序(Sorting linked list by multiple parameters)

按多个参数对链表进行排序(Sorting linked list by multiple parameters)

我试图在单链表上使用插入排序,其中每个节点有多个参数,例如:

typedef struct _node {
    char param1[10];
    char param2[10];
    char param3[10];
    struct _node *next;
} node;

该算法将通过param1对列表进行排序,并且在等效项的情况下通过param2来确定顺序,并且类似地通过param3来排序。 我无法在线找到解决此问题的方法。 对于单个参数,我有以下实现的排序算法:

void insertionSort(node **head) {

    //Initialize sorted list
    node *sorted = NULL;
    node *current = *head;

    //Insert every node into sorted list
    while (current != NULL) {
        // Store next for next iteration
        node *next = current->next;

        sortedInsert(&sorted, current);

        // Update current
        current = next;
    }

    //Replace old empty list with sorted list
    *head = sorted;
}

void sortedInsert(node **head, node *new) {
    node *current = *head;
    // Special case for the head
    if (current == NULL || strcmp(current->param1, new->param1) >= 0) {
        new->next = current;
        *head = new;
    }

    else {
        while (current->next!=NULL && strcmp(current->next->param1, new->param1) < 0){
            current = current->next;
        }

        new->next = current->next;
        current->next = new;
    }
}

我的猜测是我必须创建一个比较函数而不是以下的位,也许是一个返回0或1的整数函数,对应于这两种情况:

current->param1 >= new->param1
current->next->param1 < new->param1

但是,我无法想出这样的功能。 任何人都可以帮我解决这个问题吗?


I am trying to use insertion sort on a singly linked list, where each node has multiple parameters, say:

typedef struct _node {
    char param1[10];
    char param2[10];
    char param3[10];
    struct _node *next;
} node;

The algorithm would sort the list by param1, and in case of equivalent items decide the order by param2, and similarly by param3. I was unable to find a solution to this problem online. For a single parameter, I've got the following implementation of the sorting algorithm to work:

void insertionSort(node **head) {

    //Initialize sorted list
    node *sorted = NULL;
    node *current = *head;

    //Insert every node into sorted list
    while (current != NULL) {
        // Store next for next iteration
        node *next = current->next;

        sortedInsert(&sorted, current);

        // Update current
        current = next;
    }

    //Replace old empty list with sorted list
    *head = sorted;
}

void sortedInsert(node **head, node *new) {
    node *current = *head;
    // Special case for the head
    if (current == NULL || strcmp(current->param1, new->param1) >= 0) {
        new->next = current;
        *head = new;
    }

    else {
        while (current->next!=NULL && strcmp(current->next->param1, new->param1) < 0){
            current = current->next;
        }

        new->next = current->next;
        current->next = new;
    }
}

My guess would be that I have to create a comparison function instead of the following bits, maybe an integer function returning 0 or 1 corresponding to the two cases:

current->param1 >= new->param1
current->next->param1 < new->param1

However, I am unable to come up with such a function. Could anyone help me out with this?


原文:https://stackoverflow.com/questions/33728844
更新时间:2021-11-02 11:11

最满意答案

你需要的是一个可以处理字符串的距离函数。 查看Levenshtein距离 (编辑距离)。 那里有很多实现:

或者,你应该提取一些有趣的特征(例如:元音的数量,字符串的长度等等)来构建一个向量空间表示,然后你可以在新的上应用任何常用的距离测量(欧几里德,...)表示。


编辑

您的代码的问题是LINKAGE期望输入距离格式与PDIST的格式相匹配,即对应于1-vs-2,1-vs-3,2-vs-3等顺序的观察对的行向量..它基本上是完整距离矩阵的下半部分(因为它应该是对称的dist(1,2) == dist(2,1)

%# instances
str = {'I have a pen.'
    'I have a paper.'
    'I have a pencil.'
    'I have a cat.'};
numStr = numel(str);

%# create and fill upper half only of distance matrix
D = zeros(numStr,numStr);
for i=1:numStr
    for j=i+1:numStr
        D(i,j) = levenshtein_distance(str{i},str{j});
    end
end
D = D + D';       %'# symmetric distance matrix

%# linkage expects the output format to match that of pdist,
%# so we convert D to a row vector (lower/upper part of matrix)
D = squareform(D, 'tovector');

T = linkage(D, 'single');
dendrogram(T)

有关更多信息,请参阅相关功能的文档...


What you need is a distance function that can handle strings. Check out the Levenshtein distance (edit distance). There are plenty of implementations out there:

Alternatively, you should extract some interesting features (ex: number of vowels, length of string, etc..) to build a vector space representation, then you can apply any of the usual distance measures (euclidean, ...) on the new representation.


EDIT

The problem with your code is that LINKAGE expects the input distances format to match that of PDIST, namely a row vector corresponding to pairs of observations in the order 1-vs-2, 1-vs-3, 2-vs-3, etc.. which is basically the lower half of the complete distance matrix (since its supposed to be symmetric as dist(1,2) == dist(2,1))

%# instances
str = {'I have a pen.'
    'I have a paper.'
    'I have a pencil.'
    'I have a cat.'};
numStr = numel(str);

%# create and fill upper half only of distance matrix
D = zeros(numStr,numStr);
for i=1:numStr
    for j=i+1:numStr
        D(i,j) = levenshtein_distance(str{i},str{j});
    end
end
D = D + D';       %'# symmetric distance matrix

%# linkage expects the output format to match that of pdist,
%# so we convert D to a row vector (lower/upper part of matrix)
D = squareform(D, 'tovector');

T = linkage(D, 'single');
dendrogram(T)

Please refer to the documentation of the functions in question for more information...

相关问答

更多
  • 您可以使用连接组件标签 。 在Matlab中,假设你的矩阵只包含0和1(或者你可以这样做),你可以使用bwlabel 。 L = bwlabel(data, 8) 现在L将是一个与标签1, 2, 3...相同大小的矩阵代替1。 作为第二个参数的8表示组件的连接性。 4-connected意味着只有在方形的左侧,右侧,上方或下方,一个方形连接到另一个方格。 8-connected意味着如果正方形对角线相邻,也会连接正方形,如样本的右下角。 8是默认设置,您可以将其删除,但是如果您需要它在将来表现不同,您应该 ...
  • 由于您是机器学习/数据挖掘的新手,您不应该解决这些高级问题。 毕竟,你正在使用的数据被用于比赛(KDD Cup'99),所以不要指望它很容易! 除了数据是用于分类任务(监督式学习),其目标是预测正确的类别(不良/良好的连接)。 您似乎对聚类(无监督学习)感兴趣,这通常更困难。 这类数据集需要进行大量的预处理和巧妙的特征提取。 人们通常使用领域知识(网络入侵检测)从原始数据中获得更好的特征。直接应用简单算法(如K均值)通常会产生较差的结果。 对于初学者,您需要将属性标准化为相同的比例:在计算欧几里得距离时,作 ...
  • 你的代码适合我。 但也许你的问题是,你并没有真正改变现有文本对象的颜色,而是在旧文本对象之上创建一个新对象。 要实际删除旧对象,您需要保留句柄然后将其删除: textHandle = text(cPixel+25, rPixel+25, 'X', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle', 'FontSize', 38); delete(textHandle) 如果你真的想要改变颜色,你也可以使用句柄来做到这一点: set ...
  • 有足够的RAM可供使用,您可以在这里使用一些方法。 方法#1:使用bsxfun和bsxfun - D = squeeze(sum(bsxfun(@minus,permute(x,[3 2 1]),x).^2,2)) 方法#2:使用pdist和pdist - D = squareform(pdist(x).^2) 方法#3 matrix-multiplication based euclidean distance calculations - xt = x.'; %//' [m,n] = size(x ...
  • 至少对我来说,没有一个明显的最佳答案。 一些选项是: 正是你在做什么,逐渐附加到每个迭代的字符串 智能地增加您的累积字符串以减少重新分配的数量(@macduff答案的核心) 使用字符串的单元格数组,并智能地重新分配。 (我很确定)这只会强制重新分配指针,而不是完全重新分配字符串内容。 使用一些Java魔法来处理字符串累积。 Java库有许多有用的功能(例如StringBuilder类),但Matlab-Java接口很慢。 增量直接写入文件(我知道你已经在问题中删除了这个,但它仍然是一个有用的基线。) 我的直 ...
  • 您可以将uicontrol文本字段的位置和大小设置为数字的中心: decodedValue = 'Decoded Value: 2'; fig = figure(3); hPan = uipanel(fig,'Units','normalized'); uicontrol(hPan, 'Style','text', 'HorizontalAlignment','center', ... 'FontSize',25, 'Units','normalized', 'Position',[0.2 0.4 0. ...
  • 你需要的是一个可以处理字符串的距离函数。 查看Levenshtein距离 (编辑距离)。 那里有很多实现: Wikibooks.org FEX上的“字符串间距”的计算 或者,你应该提取一些有趣的特征(例如:元音的数量,字符串的长度等等)来构建一个向量空间表示,然后你可以在新的上应用任何常用的距离测量(欧几里德,...)表示。 编辑 您的代码的问题是LINKAGE期望输入距离格式与PDIST的格式相匹配,即对应于1-vs-2,1-vs-3,2-vs-3等顺序的观察对的行向量..它基本上是完整距离矩阵的下半部分 ...
  • 你应该在第一步有512个维度向量,每帧一个这样的向量,或者等效地是512×n矩阵。 然后在第二步中我不认为他们使用普通的内置层次聚类 - 这不是时间意识,并且不会产生间隔,加上它会扩展O(n ^ 3)这真的很糟糕 - 但相反他们使用自定义聚类算法,灵感来自层次聚类和使用Ward的链接,但它按时间间隔运行; 从单帧开始,但只加入相邻的区间 ,而不是像常规层次聚类那样的任意区间。 You should have 512 dimensional vectors at the first step, one suc ...
  • 从hclust文档中, hc$merge给出了用于创建聚类的索引,而hc$height给出了索引之间的距离。 使用USArrests作为样本数据集: hc<- hclust(dist(USArrests), method="complete") data.mat<-data.matrix(data.frame(hc$merge,hc$height)) > head(data.mat) X1 X2 hc.height [1,] -15 -29 2.291288 [2,] -17 -26 3 ...
  • 您正在使用的PCA功能(我不知道它究竟是什么),产生一个n个数字的向量。 该向量描述了图像,并且是需要给予k均值算法的。 首先,为所有100张图像运行PCA,生成nX100矩阵。 X = [] for i = 1 : 100 X(:, i) = PCA(picture...) end 如果pca返回一行而不是列,则需要 X(:, i) = PCA(picture)' k-means函数采用此参数以及簇的数量k。 所以 [idx, c] = kmeans(X, 5); 默认情况下,用于聚类的 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。