如何让我的排序算法代码工作?

问题描述 投票:0回答:0

这里的编程新手试图通过大学。我正在研究这个 JSFiddle,我正在尝试制作一个将实现排序算法的程序。以下是说明的基本概要:

你应该用 20 个元素自动填充你的列表(随机 字符串)。

完成此操作后,您将添加插入排序作为 功能。

界面应该有按钮来 (1) Repopulate the list with 随机字符串, (2) 用选择的算法 1 对列表进行排序 (3) 插入一个 用户将值输入到排序列表中。每次操作后, 应该显示新列表。

Option 4 此处将插入用户输入的新字符串(您将 需要一个文本框来输入字符串)在正确的排序位置, 你应该在屏幕上打印带有新元素的新列表。

为了一个漂亮干净的界面,你可能想创建一个包含三个的表 列并将插入按钮放在第 2 列和第 3 列以及结果上 在下面的第 2 列和第 3 列中对列表(打印在第 1 列中)进行排序 按钮。这不是必需的,但它确实给了你一个机会 查看创建界面以呈现结果的各种方法 (你会在 COP4813 中做很多这样的事情)。

当您插入“String”时,确保它插入正确的位置 排序列表之一中的位置。您可以演示插入 进入任何排序列表。

注意:您的插入功能不应在之后对整个列表进行排序 插入物。您应该将元素插入到正确的位置 您的列表,而不必求助于整个列表。这会给它 O(n) 的复杂性。


说了这么多,我已经设法得到了生成 20 个随机字符串的列表。我设法使排序算法正常工作,但绝对不是完美无缺。插入功能非常有问题。我在下面包含了 JSFiddle,请告诉我如何修复我的代码,因为我真的无法让它工作。谢谢!

这里有一些代码,所以我可以添加 jsfiddle 链接:

function insertionSort() {
        // Create a new double-linked list to hold the sorted 
        id = 0;
        var sortedList = new DblLink();

        // Iterate through the nodes in the unsorted list
        var node = dbleList.head;
        while (node != null) {
          // Find the correct position to insert the node in the sorted list
          var sortedNode = sortedList.last;
          while (sortedNode != null && sortedNode.item > node.item) {
            sortedNode = sortedNode.prev;
          }

          // Insert the node in the sorted list
          if (sortedNode == null) {
            sortedList.add(node.item);
          } else {
            var newNode = new Node(node.item);
            newNode.prev = sortedNode;
            newNode.next = sortedNode.next;
            if (sortedNode.next != null) {
              sortedNode.next.prev = newNode;
            } else {
              sortedList.last = newNode;
            }
            sortedNode.next = newNode;
            sortedList.length++;
          }

          // Move to the next node in the unsorted list
          node = node.next;
        }

https://jsfiddle.net/adrianpetria/d74tnugs/12/

javascript list algorithm sorting
© www.soinside.com 2019 - 2024. All rights reserved.