#c #algorithm #data-structures #quicksort #singly-linked-list
#c #алгоритм #структуры данных #быстрая сортировка #односвязный список
Вопрос:
/* SORTING SINGLY LINKED LIST USING QUICK SORT ALGORITHM */
/*Function to get the pivot node*/
node *partition(node *start, node *end)
{
if (start == NULL || start->next == NULL) //If one node or no node is present
{
return start;
}
node *pivot, *cur, *pre, *temp;
pivot = pre = start;
cur = start->next;
while (1)
{
if (cur == end)
{
break; //while loop breaks
}
else if (cur->data < pivot->data)
{
temp = cur;
pre->next = cur->next;
cur = cur->next; //Here swapping is done basically
temp->next = pre;
head = temp;
}
else
{
pre = cur;
cur = cur->next;
}
}
return pivot; //pivot node returned to PartitionNode in quick sort function
}
/*quicksort recursive ; what conditions do I need to apply here so the it can work properly
recursion call is not working as expected; please I ask you correct this it's been 2 days now stuck on same problem */
void *quicksort(node *head, node *tail)
{
node *start = head;
node *PartitionNode = partition(start, tail->next); //partition function called to get pivot node
node *list2 = PartitionNode->next;
while (start != PartitionNode amp;amp; list2 != tail) //not working and so much confusing please help
{
while (start->next != PartitionNode)
{
quicksort(start, PartitionNode);
node *PartitionNode = partition(start, PartitionNode);
}
while (list2 != tail) //list2 start will PartitionNode->next
{
quicksort(PartitionNode->next, tail->next);
node *PartitionNode = partition(PartitionNode->next, tail->next);
}
}
}
Комментарии:
1. функция быстрой сортировки, описанная выше, неверна и запутана. Может кто-нибудь, пожалуйста, прислать мне правильную функцию для быстрой сортировки.
2. Raminder, алгоритм быстрой сортировки хорошо известен, и вы можете найти множество примеров в Интернете. Вот один, который я нашел, в который также были переданы некоторые данные. Может быть, вы могли бы попробовать это и посмотреть, работает ли это для вас. geeksforgeeks.org/quick-sort
Ответ №1:
node *partition(node *start, node *end) //pivot is first element of linked list
{
node *pivot_prev = start;
node *current = start;
int pivot = start->data;
start = start->next;
while (start != end->next)
{
if (start->data < pivot)
{
pivot_prev = current;
int temp = current->data;
current->data = start->data;
start->data = temp;
current = current->next;
}
start = start->next;
}
return pivot_prev; //current not will not be returned as current not is already at its right place
}
void quicksort(node *start, node *end)
{
if (start == end)
{
return;
}
node *prev = partition(start, end);
quicksort(start, prev);
quicksort(prev->next, end);
}
Комментарии:
1. (Даже видя, что это выглядит чище:) Пожалуйста, опишите, что изменилось и почему это имеет значение.
2. @greybeard проблема заключалась в повторном вызове n сводного адреса, который требовался для сортировки связанного списка. В предыдущей функции быстрой сортировки условие рекурсивного вызова не инициируется должным образом и не завершается. Более того, сводный адрес, возвращающий функцию frm partition, также неверен. Поэтому я запускаю алгоритм. В новом алгоритме я вернул правильный pivot n, затем рекурсивно вызвал функцию быстрой сортировки, сначала запустив frm head до tail n получил 1-й pivot addr frm it n затем быстрая сортировка запускается для начала до поворота и быстрой сортировки из piviot-> next до хвоста. Этот процесс повторяется рекурсивно и завершается, когда start достигает end .