# c: Selection sort on a linklist?

97 views

I have a data-structure as linklist which has elements as integer. I want to sort this linklist using selection sort, can someone help me.

posted Oct 15, 2014

+1 vote

Selection short first finds the smallest element in the array and exchanges
it with the element in the first position, then find the second smallest
element and exchange it with the element in the second position, and
continues in this way until the entire array is sorted.

Apply the same on link list, where we have to compare each link list
element, and have to swap the link list elements.

Here is my code (tested) :)

``````#include <stdio.h>
#include <stdlib.h>

int data;
}Node;

void swap(Node *x, Node *y);

int main()
{
int num, num_elem, i;

printf("Enter number of elements: ");
scanf("%d", &num_elem);

printf("Enter %d number one by one:\n", num_elem);
for (i = 0; i < num_elem; i++) {
scanf("%d", &num);
}

printf("Displaying link list before sorting :\n");

printf("Displaying link list after sorting :\n");

return 0;
}

// Function to create node
{
Node *front, *tail;

tail = malloc(sizeof(Node));
if (tail == NULL) {
printf("Malloc fails ...\n");
return;
}

tail->data = num;
tail->next = NULL;

} else {
while (front->next != NULL)
front = front->next;

front->next = tail;
}
}

// Swaping of data between two nodes.
void swap(Node *x, Node *y)
{
int temp;

temp = x->data;
x->data = y->data;
y->data = temp;
}

//    Performing selection sort
{
Node  *i, *j, *min;

for (i = head; i != NULL && i->next != NULL; i = i->next) {
min = i;

for (j = i->next; j != NULL; j = j->next) {
if (j->data < min->data) {
min = j;
}
}

if (min != i) { // Ignore swaping at the same list.
swap(min, i);
}
}
}

{
}
printf("\n");
}

// Freeing up the allocated node.
{
Node *temp;