Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Created January 24, 2022 08:54
Show Gist options
  • Save piusayowale/40ea4010b76c993f2609d6c85a4045ee to your computer and use it in GitHub Desktop.
Save piusayowale/40ea4010b76c993f2609d6c85a4045ee to your computer and use it in GitHub Desktop.
Linked list selection sort 2
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
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->next = nullptr;
temp->value = value;
ptr->next = temp;
return list;
}
Node* sort(Node*& list) {
Node* current = list;
Node* smallest = nullptr;
Node* next = nullptr;
while (current != nullptr)
{
smallest = current;
next = current;
while (next != nullptr)
{
if (next->value < smallest->value) {
smallest = next;
}
next = next->next;
}
swap(&smallest->value, &current->value);
current = current->next;
}
return list;
}
void transverse(Node* list) {
while (list != nullptr)
{
std::cout << list->value << " ";
list = list->next;
}
}
int main() {
Node* list = nullptr;
list = insert(list, 0);
list = insert(list, 9);
list = insert(list, 8);
list = insert(list, 7);
list = insert(list, 6);
list = insert(list, -1);
sort(list);
transverse(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment