I have come across a fun puzzle, sorting a linked list, and I wanted to go for quicksort. However, I am not quite sure whether my partitioning algorithm is efficient enough. I also believe that my code is not clean.
Is it possible to remove some variables or make it more efficient?
#include <iostream>
#include <cstdlib>
using namespace std;
struct Node
{
int data;
Node *next;
};
void printList(Node *list)
{
Node *temp = list;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
int partition(Node *list, int start, int end)
{
Node *startPtr = list, *endPtr = list, *head = list;
for(int i = 0; i < start; i++)
if(startPtr == NULL || startPtr->next == NULL)
return -1;
startPtr = startPtr->next;
for(int i = 0; i < end; i++)
{
if(endPtr == NULL || endPtr->next == NULL)
return -1;
endPtr = endPtr->next;
}
Node *temp = NULL, *temp2 = startPtr;
int pivot = endPtr->data;
while(temp2->next != endPtr)
{
if(temp2->data < pivot)
{
if(temp != NULL)
temp = temp->next;
else
temp = startPtr;
swap(temp->data, temp2->data);
}
temp2 = temp2->next;
}
temp = temp->next;
swap(temp->data, endPtr->data);
int index;
Node *temp3 = list;
for(index = 0; temp3->data != pivot; index++)
temp3 = temp3->next;
return index;
}
int main()
{
Node *a = new Node;
Node *b = new Node;
Node *c = new Node;
Node *d = new Node;
Node *e = new Node;
Node *f = new Node;
a->next = b;
a->data = 2;
b->next = c;
b->data = 6;
c->next = d;
c->data = 3;
d->next = e;
d->data = 1;
e->next = f;
e->data = 7;
f->data = 5;
cout<<partition(a, 0, 5)<<endl;
return 0;
}
for
loop in the functionpartition
. – Uwe Plonus Jul 2 '13 at 11:26printList
is unused... – William Morris Jul 3 '13 at 13:49