如何在链表上执行选择排序
How to execute a Selection Sort on a linked list?
我试图在链表上实现选择排序。我希望它直接在链表上执行,而不是复制,使用节点指针而不是我粘贴在这里的数组索引方法:
void listClass::selectionsort(int array[], int size)
{
int startscan, minIndex, minValue;
for (startscan = 0; startscan < (size - 1); startscan++)
{
minIndex = startscan;
minValue = array[startscan];
for (int index = startscan + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startscan];
array[startscan] = minValue;
}
}
我如何调整这个函数来接受我的链表?然后分类?我也不想使用任何类型的STL容器
假设列表为{90,13,5,12}。
{* 90,13,5,12}
找到指针后面最小的成员,并将其移到指针前面。
{5, * 90,13,12}
找到指针后面最小的成员,并将其移到指针前面。
{5,12, * 90,13}
。
{5,12,13, * 90}
。
{5,12,13,90}
指针指向列表的末端,我们完成了,列表被排序了
这是不使用STL的链表选择排序的c++实现。为了方便不同情况下的程序测试,这个程序创建了一个给定大小的随机数字链表。
//Program to sort a linked list using selection sort.
#include<stdio.h>
#include<time.h>
#include<cstdlib>
#define size 10 //Size of linked list.
struct node
{
int info;
struct node *next;
}*start=NULL;
typedef struct node * Node;
int main()
{
int i;
Node ptr;
void selectionsort(Node);
srand(time(NULL));
for(i=0;i<size;i++)
{
Node ptr,temp;
ptr=(Node)malloc(sizeof(node));
ptr->info=rand()%100; //Random linked list of given size is created.
ptr->next=NULL;
if(start==NULL)
{
start=ptr;
}
else
{ temp=start;
while(temp->next!=NULL)
temp=temp->next;
temp->next=ptr;
}
}
printf(" Linked List Before Sorting Is -n");
ptr=start;
while(ptr!=NULL)
{
printf(" %d ",ptr->info);
ptr=ptr->next;
}
printf("n Linked List After Sorting Is -n");
selectionsort(start);
ptr=start;
while(ptr!=NULL)
{
printf(" %d ",ptr->info);
ptr=ptr->next;
}
return 0;
}
void selectionsort(Node start)
{
Node ptr=start,temp,address;
int var;
while(ptr->next!=NULL)
{
temp=ptr;
address=temp;
while(temp!=NULL)
{
if((address->info)>(temp->info))
address=temp;
temp=temp->next;
}
var=address->info;
address->info=ptr->info;
ptr->info=var;
ptr=ptr->next;
}
}
详细信息请访问-https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 如何使用默认参数等选择模板专业化
- 选择在CMAKE中构建库或可执行文件
- 执行默认值:在C 中的开关案例选择语句中
- 您如何选择在opencv-dnn上执行操作的设备
- 在什么条件下,数据库在从 cpp 执行选择查询时不会关闭游标
- C 编译器如何在延期和异步执行std :: async之间进行选择
- 如何将音频与功率谱同步并选择帧长度 N(执行 fft)
- 选择零件的策略要执行C
- 使用用户定义的函数对循环/对称值执行Sqlite(C API)和查询(选择)
- 如果我已经完成了当前功能,我该如何选择继续执行另一个功能
- 为什么 Google 测试会自动执行未选择的测试用例
- 当选择一个选项时,如何执行另一个c++程序
- c++链接器如何选择将类的哪个定义链接到可执行文件中
- 选择并执行Qt中QListWidget上显示的MIDI文件
- 是否有可能使用模板元编程在编译时选择类将要执行的功能?
- 如何在链表上执行选择排序
- 游戏有时不会执行随机选择的策略
- 执行while循环,如果用户选择yes行为不正确,则重新启动程序
- 如何在分叉和执行后使用带有选择的管道