C
Algorithm
Data structure
Write in the file 0-nth
, the big O notations of the time complexity of the Bubble sort algorithm, with 1 notation per line:
- in the best case
- in the average case
- in the worst case
- Prototype:
void bubble_sort(int *array, size_t size);
- You’re expected to print the array after each time you swap two elements (See example below)
- Check for special cases:- If
array
is NULL orsize
is 0, return immediately. - Initialize variables:-
i
,j
,size_i
,temp
, andflag
are declared for later use. - Calculate
size_i
:- Setsize_i
tosize - 1
. - Start the outer loop:- Loop through the array using
i
from 0 tosize - 1
. - Initialize
flag
and start the inner loop:- Setflag
to 0 at the beginning of each pass and loop through the array usingj
from 0 tosize_i
. - Compare adjacent elements and swap if necessary:- If
array[j] > array[j + 1]
, swap them and print the array. - Check for sorted array:- If
flag
remains 0 after the inner loop, return early as the array is sorted. - Decrement
size_i
:- After each pass, decrementsize_i
by 1 to consider a shorter unsorted portion. - Repeat the outer loop until sorted:- Continue the outer loop until
i
reachessize - 1
. - Return:- The function exits when the array is fully sorted or when a sorted portion is detected.
Write a function that sorts a doubly linked list
of integers in ascending order using the Insertion sort algorithm
- Prototype:
void insertion_sort_list(listint_t **list);
- You are not allowed to modify the integer n of a node. You have to swap the nodes themselves.
- You’re expected to print the list after each time you swap two elements.
-
Input Validation:- Check if the input list (
list
) is empty (NULL). If it is, there's nothing to sort, so return early. -
Initialization:- Initialize two pointers,
node1
andnode2
, to traverse the list. -
Main Loop:- Start a loop that iterates through the list as long as there is a
node1->next
. -
Comparison:- Compare the value (
n
) of the current node (node1
) with the value of the next node (node2
). -
Insertion Condition:- If
node1
has a greater value thannode2
, it meansnode2
should be inserted beforenode1
to maintain sorted order. -
Updating Pointers for Insertion:- Update the
prev
andnext
pointers ofnode1
,node2
, and their neighboring nodes to insertnode2
beforenode1
. -
Continue Iteration:- After each comparison and possible insertion, move
node1
to the next position in the list. -
Completion:- Once the loop finishes, the list is sorted, and the function is done.