Created
January 23, 2022 06:10
-
-
Save piusayowale/54a459a5ad34b7f5c2b0b333656e2c3f to your computer and use it in GitHub Desktop.
Selection sort on linked list
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
struct Node { | |
int value; | |
Node* next; | |
}; | |
Node* insert(Node*& list, int value) { | |
Node* temp = nullptr; | |
Node* ptr = list; | |
if (ptr == nullptr) { | |
temp = new Node; | |
temp->value = value; | |
temp->next = nullptr; | |
list = temp; | |
return list; | |
} | |
while (ptr->next != nullptr) | |
{ | |
ptr = ptr->next; | |
} | |
temp = new Node; | |
temp->value = value; | |
temp->next = NULL; | |
ptr->next = temp; | |
return list; | |
} | |
void print(Node* list) { | |
while (list != nullptr) | |
{ | |
std::cout << list->value << " "; | |
list = list->next; | |
} | |
std::cout << "\n"; | |
} | |
bool search(Node*& list, int value, Node *& ptr_out) { | |
ptr_out = list; | |
if (list == nullptr) { | |
return false; | |
} | |
while (ptr_out != nullptr && ptr_out->value != value) | |
{ | |
ptr_out = ptr_out->next; | |
} | |
if (ptr_out == nullptr) { | |
return false; | |
} | |
return true; | |
} | |
void swap(Node** first, Node** second) | |
{ | |
Node* tmp = *first; | |
*first = *second; | |
*second = tmp; | |
} | |
Node* swap(Node*& list, int a, int b) { | |
Node** pos_a = nullptr; | |
Node** pos_b = nullptr; | |
Node** ptr = &list; | |
Node** ptr2 = &list; | |
while ((*(ptr)) != nullptr) | |
{ | |
if ((*(ptr))->value == a) { | |
pos_a = ptr; | |
break; | |
} | |
ptr = &(*(ptr))->next; | |
} | |
while ((*(ptr2)) != nullptr) | |
{ | |
if ((*(ptr2))->value == b) { | |
pos_b = ptr2; | |
break; | |
} | |
ptr2 = &(*(ptr2))->next; | |
} | |
if (pos_a == nullptr || pos_b == nullptr) { | |
return nullptr; | |
} | |
swap(pos_a, pos_b); | |
swap(&(*pos_a)->next, &(*pos_b)->next); | |
return list; | |
} | |
void selectionSort(Node*& head) | |
{ | |
Node* temp = head; | |
while (temp) { | |
Node* min = temp; | |
Node* r = temp->next; | |
while (r) { | |
if (min->value > r->value) | |
min = r; | |
r = r->next; | |
} | |
int x = temp->value; | |
temp->value = min->value; | |
min->value = x; | |
temp = temp->next; | |
} | |
} | |
int main() { | |
Node* list = nullptr; | |
list = insert(list, 6); | |
list = insert(list, 8); | |
list = insert(list, 2); | |
list = insert(list, 1); | |
list = insert(list, 9); | |
list = insert(list, 7); | |
list = insert(list, 0); | |
print(list); | |
list = swap(list, 1, 0); | |
print(list); | |
selectionSort(list); | |
print(list); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment