Sorting Linked Lists
In questa pagina 6
Task: sort a list in ascending (or descending) order.
Input: 10->30->20->5 Output: 5->10->20->30
Input: 20->4->3 Output: 3->4->20Techniques covered: bubble sort, insertion sort, quick sort, merge sort. For each the slides show the array version first, then the list version. Node used:
struct Node {
int data;
struct Node* next;
};Complexity notation: see Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →. List basics: Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →.
Swap macro
#define SWAP(a, b) \
int temp = a; \
a = b; \
b = temp;The slide shows this first and then the safe version, which wraps the body in do { ... } while (0) so that the macro behaves like a single statement (usable e.g. after an if without braces) and temp stays in its own block:
#define SWAP(a, b) \
do { \
int temp = a; \
a = b; \
b = temp; \
} while (0)Bubble sort
Repeatedly swap adjacent elements that are in the wrong order. After the first pass the largest element is at the right end, then the second largest, and so on. Not suitable for large data sets (high average and worst-case time).
Array version, with an early exit when a pass makes no swap:
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
SWAP(arr[j], arr[j + 1]);
swapped = true;
}
}
if (swapped == false) // no swap in the inner loop: already sorted
break;
}
}(bool needs <stdbool.h>; the slide does not show the include.)
Recursive version: one pass bubbles the largest to the end, then recursion on the first n-1 elements; stops if n == 1 or no swap occurred (count == 0):
void bubbleSort(int arr[], int n)
{
// Base case
if (n == 1)
return;
int count = 0;
// One pass of bubble sort. The largest element is moved (bubbled) to the end.
for (int i=0; i<n-1; i++)
if (arr[i] > arr[i+1]){
SWAP(arr[i], arr[i+1]);
count++;
}
// If no swap happened, return
if (count==0)
return;
// Largest element is fixed, recursion for remaining array
bubbleSort(arr, n-1);
}Method 1: bubble sort on a linked list
Compare adjacent nodes and swap the actual nodes (relink), not just the data. Time O(n^2), auxiliary space O(1).
int bubbleSort(struct Node** ptr) // A version of Bubble Sort
{
struct Node* prev;
struct Node* current;
struct Node* tmp;
bool swapped = true;
if (*ptr == NULL || (*ptr)->next == NULL)
return(0);
while (swapped)
{
swapped = false;
current = (*ptr)->next;
if ((*ptr)->data > current->data) // first two nodes: the head changes
{
swapped = true;
prev = *ptr;
*ptr = current;
prev->next = current->next;
current->next = prev;
}
prev = *ptr;
current = prev->next->next;
while (current != NULL)
{
if (prev->next->data > current->data)
{
swapped = true;
tmp = prev->next;
prev->next = current;
tmp->next = current->next;
current->next = tmp;
}
prev = prev->next;
current = current->next;
}
if (!swapped)
break;
}
return(0);
}Reading it: the list of 0 or 1 nodes is already sorted. The head pair is handled separately because swapping it changes *ptr (hence struct Node**). The inner loop keeps prev one node before the pair (prev->next, current) so that the pair can be swapped with three pointer assignments.
Exercise (slide): given a singly linked list of strings
struct Node {
char *s;
struct Node *next;
};implement bubble sort to order it in non-decreasing order (compare with strcmp instead of >; no solution on the slide).
Insertion sort
Like sorting playing cards in the hand: the array is virtually split into a sorted and an unsorted part; each value from the unsorted part is placed at its place in the sorted part (compare the key with its predecessors, shift greater elements one position up). Slide example: {18, 15, 23, 6, 9}: 15 18 23 6 9, then 15 18 23 6 9 (23 already in place), then 6 15 18 23 9, then 6 9 15 18 23.
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1] that are greater than key
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}Method 2: insertion sort on a linked list
- Create an empty sorted (result) list.
- Traverse the given list; for every node, insert it in sorted way in the result list (the ordered insertion
insertInOrderof Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →). - Change the head of the given list to the head of the result list.
Time O(n^2), auxiliary space O(1) (nodes are relinked, not copied). The slides give no code for this method.
Quick sort
Divide and conquer: pick a pivot, partition() puts the pivot in its final position with smaller elements to its left and greater to its right, then recurse on both sides.
Pivot choices: first element, last element (used below), random element, middle element.
int partition(int arr[],int low,int high)
{
//choose the pivot
int pivot=arr[high];
//index of smaller element = right position of pivot found so far
int i=(low-1);
for(int j=low;j<=high;j++)
{
//if current element is smaller than the pivot
if (arr[j]<pivot)
{
//Increment index of smaller element
i++;
SWAP(arr[i],arr[j]);
}
}
SWAP(arr[i+1],arr[high]);
return (i+1);
}
void quickSort(int arr[],int low,int high)
{
// when low is less than high
if (low<high)
{
// pi is the partition return index of pivot
int pi=partition(arr,low,high);
// smaller elements go left, higher elements go right
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}Slide trace for 10, 80, 30, 90, 40, 50, 70 with pivot 70: 10 < 70 (swap with itself); 80 no; 30 < 70 swap(80,30) -> 10 30 80 90 40 50 70; 90 no; 40 < 70 swap(80,40) -> 10 30 40 90 80 50 70; 50 < 70 swap(90,50) -> 10 30 40 50 80 90 70; last swap(80,70) -> 10 30 40 50 70 90 80, returns 4. Then quickSort(arr,0,3) and quickSort(arr,5,6).
Method 3: quick sort on a linked list
partitiontakes the last node as pivot; traverse the list: a node smaller than the pivot stays where it is; a node with greater value is moved after the tail. Return the pivot node.- Find the tail of the list on the left of the pivot and recurse on the left list; then recurse on the right list.
- Return the head of the list obtained by joining left and right.
Time O(n^2), auxiliary space O(1). The slides show only partition (the recursive driver is not on the slides):
// Function to partition the list and return the pivot node
struct Node* partition(struct Node* head, struct Node* end, struct Node** newHead, struct Node** newEnd) {
struct Node* pivot = end;
struct Node* prev = NULL, * cur = head, * tail = pivot;
// Nodes smaller than the pivot will be moved to the front
while (cur != pivot) {
if (cur->data < pivot->data) {
// Move node to the new head
if ((*newHead) == NULL) {
(*newHead) = cur;
}
prev = cur;
cur = cur->next;
}
else {
// Move node to the end of the list
if (prev) {
prev->next = cur->next;
}
struct Node* temp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = temp;
}
}
// If the new head hasn't been updated, it is the pivot
if ((*newHead) == NULL) {
(*newHead) = pivot;
}
// Update the new end to the current tail
(*newEnd) = tail;
return pivot;
}Merge sort
Divide the list in two halves, sort each half, merge the sorted halves. A one-element list is already sorted. Merge sort on a list changes next links (not data), so the head may change: it needs a reference to the head (headRef).
MergeSort(headRef):
if head is NULL or has one element: return
split into two halves a and b (FrontBackSplit)
MergeSort(a); MergeSort(b)
*headRef = SortedMerge(a, b)Split with slow/fast pointers: fast moves two nodes while slow moves one; when fast reaches the end, slow is at the middle.
void splitList(struct Node* source, struct Node** frontRef, struct Node** backRef) {
struct Node* slow;
struct Node* fast;
slow = source;
fast = source->next;
// Move fast two nodes and slow one node
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
// Split the list into two halves
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}Driver:
void mergeSort(struct Node** headRef) {
struct Node* head = *headRef;
struct Node *a;
struct Node* b;
// Base case: if the list is empty or has a single element
if ((head == NULL) || (head->next == NULL)) {
return;
}
// Split the list into two halves
splitList(head, &a, &b);
// Recursively sort the two halves
mergeSort(&a);
mergeSort(&b);
// Merge the sorted halves
*headRef = sortedMerge(a, b);
}Recursive merge of two sorted lists (<= keeps equal elements in their original order):
struct Node* sortedMerge(struct Node* a, struct Node* b) {
struct Node* result = NULL;
if (a == NULL)
return b;
else if (b == NULL)
return a;
if (a->data <= b->data) {
result = a;
result->next = sortedMerge(a->next, b);
} else {
result = b;
result->next = sortedMerge(a, b->next);
}
return result;
}Recursion background: Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →. The slides do not give a complexity figure for merge sort on lists.
Summary of the list methods (from the slides)
| Method | Idea on a list | Time | Aux. space |
|---|---|---|---|
| 1 Bubble | swap adjacent nodes | O(n^2) | O(1) |
| 2 Insertion | build a sorted result list, insert each node in order | O(n^2) | O(1) |
| 3 Quick | partition around the last node, larger nodes moved after the tail | O(n^2) | O(1) |
| 4 Merge | split (slow/fast), sort halves, sortedMerge |
not stated | not stated |
Versione ripasso
- Sort lists by relinking nodes, not by copying data. Node:
struct Node { int data; struct Node* next; };. Functions that may change the head takestruct Node**(Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →). Complexity notation: Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →. Examples:10->30->20->5gives5->10->20->30. SWAPmacro: the safe form is#define SWAP(a, b) do { int temp = a; a = b; b = temp; } while (0), which works as one statement, for example after anifwithout braces.- Bubble (array): swap adjacent out-of-order items, the largest goes to the end after each pass, stop early when a pass has no swap. Not for large data (high average and worst-case time).
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) SWAP(arr[j], arr[j + 1]);- Bubble (list): compare adjacent nodes and relink them, O(n^2) time, O(1) auxiliary space. The head pair is special, because swapping it changes
*ptr(hencestruct Node**). The inner loop keepsprevone node before the pair, so three pointer assignments swap it. A list of 0 or 1 nodes is already sorted. - Insertion (array): the prefix is sorted; for each
key = arr[i], shift the greater elements one step to the right and put the key in the gap. Example{18, 15, 23, 6, 9}gives6 9 15 18 23in the end. - Insertion (list): create an empty result list, take each node of the input and insert it with ordered insertion (Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →), then make the result list the new head. O(n^2), O(1) space, nodes relinked and not copied.
- Quick (array): pick a pivot (first, last, random or middle; the code uses the last),
partitionmoves the smaller items to the left withiand then puts the pivot ati + 1, which is its final place; recurse onlow..pi-1andpi+1..high. Slide trace:10 80 30 90 40 50 70with pivot 70 gives10 30 40 50 70 90 80, pivot at index 4. - Quick (list):
partition(head, end, &newHead, &newEnd)takes the last node as pivot and walks the list: a node smaller than the pivot stays where it is, a larger one is moved after the tail. It returns the pivot node. The recursive driver is not on the slides. O(n^2) time, O(1) auxiliary space. - Merge sort on a list: base case, a
NULLlist or one node is sorted. Split in two halves, sort each, merge. The split needsslow(one step) andfast(two steps) pointers: whenfastreaches the end,slowis at the middle, then*frontRef = source; *backRef = slow->next; slow->next = NULL;. - Driver:
mergeSort(struct Node** headRef)callssplitList, recurses onaandb, then sets*headRef = sortedMerge(a, b). The merge is recursive: it takes the smaller head,<=keeps equal items in their original order (Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →). The slides give no complexity for merge sort on lists. - Summary: bubble, insertion and quick on lists are O(n^2) with O(1) extra space; merge sort is the cleanest choice for lists.
- Exercise: bubble sort of a list of strings (
struct Node { char *s; struct Node *next; };), in non-decreasing order, usingstrcmpinstead of>. - Typical errors: empty or one-node list not handled; forgetting to update the head;
sortedMergewith<loses the stability; comparing strings with>on pointers instead ofstrcmp; splitting the list without cuttingslow->nexttoNULL.