Created
May 26, 2017 19:16
-
-
Save muhammedeminoglu/b6e38c66d034374661e33fe191b846b0 to your computer and use it in GitHub Desktop.
Selection Sort on Linked Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct node{ | |
int data; | |
struct node *next; | |
}; | |
struct node* start = NULL; | |
//I dont want to traverse for add an item last position, i will use last->next | |
struct node* last = NULL; | |
struct node* temp; | |
struct node* createNode(int x) | |
{ | |
struct node* newNode = (struct node*)malloc(sizeof(struct node)); | |
newNode->data = x; | |
newNode->next = NULL; | |
return newNode; | |
} | |
void addLast(int y) | |
{ | |
struct node* hodor = createNode(y); | |
if(start == NULL) | |
{ | |
start = hodor; | |
last = hodor; | |
} | |
else | |
{ | |
last->next = hodor; | |
last = hodor; | |
} | |
} | |
void printLinked() | |
{ | |
temp = start; | |
while(temp->next != NULL) | |
{ | |
printf("%d\n", temp->data); | |
temp = temp->next; | |
} | |
printf("%d\n", temp->data); | |
} | |
void init(int size) | |
{ | |
int i, number; | |
for( i = 0; i < size; i++ ) | |
{ | |
number = rand()%10000; | |
addLast(number); | |
} | |
} | |
void selectionLinked() | |
{ | |
struct node* key; | |
key = start; | |
while(key != NULL) | |
{ | |
temp = key->next; | |
while(temp != NULL) | |
{ | |
if(key->data > temp->data) | |
{ | |
swapNode(key, temp); | |
} | |
temp = temp->next; | |
} | |
key = key->next; | |
} | |
} | |
void swapNode(struct node *x, struct node *y) | |
{ | |
int temp = x->data; | |
x->data = y->data; | |
y->data = temp; | |
} | |
int main() | |
{ | |
int choise; | |
while( 1 == 1) | |
{ | |
printf("\n How many numbers do you want to create ... "); | |
scanf("%d", &choise); | |
init(choise); | |
selectionLinked(); | |
printLinked(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment