Arrays 对数组进行排序并将其放入链接列表中

Arrays 对数组进行排序并将其放入链接列表中,arrays,algorithm,sorting,linked-list,Arrays,Algorithm,Sorting,Linked List,我有一个伪代码算法,它将未排序的数组作为输入,并将其排序到一个链表中。我不太明白它是怎么工作的。也许这里面有错误。我已经试了一个多小时来理解它是如何工作的,但我在某个点上被卡住了。我会尽可能多地解释。任何知道它是如何工作的人都乐意帮忙 ORDER(A) head [L1] = create(); //Null List is created. key[head[L1]] = A[1]; //First element of the array is put as the first

我有一个伪代码算法,它将未排序的数组作为输入,并将其排序到一个链表中。我不太明白它是怎么工作的。也许这里面有错误。我已经试了一个多小时来理解它是如何工作的,但我在某个点上被卡住了。我会尽可能多地解释。任何知道它是如何工作的人都乐意帮忙

ORDER(A)
head [L1] = create();    //Null List is created.
key[head[L1]] = A[1];    //First element of the array is put as the first in list.

for i=2 to length(A);
    x = create();        // create a node for every element of the array
    key[x] = A[i];       // put A[i] as key in the node.
    p1 = head[L1];       // make p1 head of the list.
    if key[p1] > A[i];       //compare A[i] with the head
       insert_head(x);      // if smaller put it in the beggining and make it head
    while key[next[p1]] < A[i] AND next[p1] =/= nil  // This part I don't understand 
       if next[p1] == nil                               //very well.
          next[p1] = x
          next[x] = nil
       else
          next[x] = next[p1]
          next[p1] = x;
订单(A) 头[L1]=创建()//创建空列表。 键[head[L1]]=A[1]//数组的第一个元素作为列表中的第一个元素。 对于长度(A),i=2; x=创建();//为数组的每个元素创建一个节点 键[x]=A[i];//将[i]作为键放入节点中。 p1=头[L1];//让p1成为名单的头号人物。 如果键[p1]>A[i]//将A[i]与头部进行比较 插入_头(x);//如果更小,就把它放在壁炉里,让它头像 而键[next[p1]]它与

链表被排序并开始为空,然后数组中的每个元素被插入到链表的正确位置,以便在每次插入后对其进行排序

对于insert,它将遍历链表,直到我们要插入的元素小于链表中的当前元素,或者到达链表的末尾,然后插入

我确实认为可能存在错误,我认为while循环应该是:

// here we advance the position in the linked-list
//   until we reach the end or the current element is smaller
while key[next[p1]] < A[i] AND next[p1] =/= nil
  p1 = next[p1]

// if we reached the end, next[x] won't point to anything
if next[p1] == nil                          
  next[p1] = x
  next[x] = nil
// if we didn't reach the end,
//   next[x] needs to point to anything what next[p1] was pointing to
else
  next[x] = next[p1]
  next[p1] = x;
//在这里,我们推进链接列表中的位置
//直到我们到达终点或者当前元素变小
而键[next[p1]]
您拥有的伪代码是的一个实现,它的最坏情况复杂性为O(n^2)

基本上,while块循环保存已排序数据子集的整个列表,当while找到要插入的点时,它会将其插入已排序列表中。如果while没有找到要插入的位置,它会将其插入列表的末尾

也许你应该考虑使用(复杂性o(n Log-n)),然后把它传递给一个列表(o(n))


此方案的总复杂度为O(n logn)

对数组进行排序并将其放入链表中
获取未排序的数组并将其放入已排序的链表中
?获取未排序的数组并将其放入已排序的链表中。此算法有O(n^2),可以在O(n logn-n)中表示使用更好的算法对数组排序,然后将其传递给list@Qsebas从学习的角度来看,所有O(n^2)算法(bubblesort、选择排序、插入排序)的优点是它们简单且易于实现。此外,对于小型阵列(少于100个元素),选择和插入排序通常比分治算法性能更好,因为它们的开销更低。解决新学员排序问题的错误方法是只关注时间复杂性。