The program works perfectly.

But in order for an individual to succeed in computer science, he or she must fiddle around with the program, and come up with other algorithms, such as converting a pre existing one, even it it is more or less efficient.

Again the program works perfectly.

The program, is to use a selection/ or insertion, sort algorithm, and sort a linked list of integers in ascending or descending order.

Here is the for loop version of the algorithm.

```
void listSort(struct listNode *head, SortOrder order)
{
struct listNode *i,
*j,
*min;
for (i = head; i->next != NULL; i = i->next)
{
min = i;
for (j = i->next; j->next != NULL; j = j->next) {
if (order == ASCENDING) {
if (*(j->next) < *(min->next)) min = j;
} else {
if (*(j->next) > *(min->next)) min = j;
}
}
nodeSwap(i,min);
}
}
```

Now, I'd like to convert both of those for loops to a while loop. For now though, I'm focusing on the outer/first for loop, an I am stuck.

```
void listSort(struct listNode *head, SortOrder order)
{
struct listNode *i,
*j,
*min;
//for (i = head; i->next != NULL; i = i->next)
i = head->next; // I added this
while (i)
{
min = i;
for (j = i->next; j->next != NULL; j = j->next)
{
if (order == ASCENDING)
if (*(j->next) < *(min->next)) min = j;
else
if (*(j->next) > *(min->next)) min = j;
}
i->next = i; // I added this
nodeSwap(i,min);
}
}
```

The program, only lists the original order of integers. Basically the program doesn't sort or display anything wihth the latter modification.

This is the nodeSwap function

```
bool nodeSwap(struct listNode *p, struct listNode *q) {
struct listNode *t1, *t2, *t3;
bool swapped = false;
if (p != q) {
t1 = p->next; t2 = q->next; t3 = q->next->next;
p->next = q->next;
q->next = t1;
t2->next = t1->next;
t1->next = t3;
swapped = true;
}
return swapped;
}
```

*Edited 4 Years Ago by coroshea*