Created
January 24, 2022 08:54
-
-
Save piusayowale/40ea4010b76c993f2609d6c85a4045ee to your computer and use it in GitHub Desktop.
Linked list selection sort 2
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
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, ¤t->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