gpt4 book ai didi

c++ - 这是什么排序算法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:22 25 4
gpt4 key购买 nike

更新:好的,我看到它是一种冒泡排序,但它是否效率较低,因为当特定运行没有交换时它不会停止?它一直运行到 first 为空。

你好,我有一个排序算法如下。我的问题是,这是哪种排序算法?我认为这是冒泡排序,但它不会进行多次运行。任何的想法?谢谢!

//sorting in descending order
struct node
{
int value;
node* NEXT;
}
//Assume HEAD pointer denotes the first element in the //linked list
// only change the values…don’t have to change the //pointers

Sort( Node *Head)
{
node* first,second,temp;
first= Head;
while(first!=null)
{
second=first->NEXT;
while(second!=null)
{
if(first->value < second->value)
{
temp = new node();
temp->value=first->value;
first->value=second->value;
second->value=temp->value;
delete temp;
}
second=second->NEXT;
}

first=first->NEXT;
}
}

最佳答案

让我们让算法更清晰:

Sort {
first = head;
while (first ≠ NULL) {
next = first.next
while (next ≠ NULL) {
if (first.value < next.value)
swap first.value and next.value
advance next
}
advance first
}
}

这是一种非常低效的插入排序实现。


揭示插入排序特征的运行示例:

5 → 2 → 3 → 1 → nil
^ ^
f n [swap]

2 → 5 → 3 → 1 → nil
^ ^
f n

2 → 5 → 3 → 1 → nil
^ ^
f n [swap]

1 → 5 → 3 → 2 → nil
^ ^
f n

1 → 5 → 3 → 2 → nil // insert the minimum value 1 to the beginning of the sublist
^ ^
f n [swap]

1 → 3 → 5 → 2 → nil
^ ^
f n [swap]

1 → 2 → 5 → 3 → nil // insert the minimum value 2 to the beginning of the sublist
^ ^
f n

1 → 2 → 5 → 3 → nil
^ ^
f n [swap]

1 → 2 → 3 → 5 → nil // insert the minimum value 3 to the beginning of the sublist
^ ^
f n

1 → 2 → 3 → 5 → nil // insert the minimum value 5 to the beginning of the sublist
^ ^
f n

1 → 2 → 3 → 5 → nil
^
f

关于c++ - 这是什么排序算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2529999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com