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
arrayis NULL orsizeis 0, return immediately. - Initialize variables:-
i,j,size_i,temp, andflagare declared for later use. - Calculate
size_i:- Setsize_itosize - 1. - Start the outer loop:- Loop through the array using
ifrom 0 tosize - 1. - Initialize
flagand start the inner loop:- Setflagto 0 at the beginning of each pass and loop through the array usingjfrom 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
flagremains 0 after the inner loop, return early as the array is sorted. - Decrement
size_i:- After each pass, decrementsize_iby 1 to consider a shorter unsorted portion. - Repeat the outer loop until sorted:- Continue the outer loop until
ireachessize - 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,
node1andnode2, 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
node1has a greater value thannode2, it meansnode2should be inserted beforenode1to maintain sorted order. -
Updating Pointers for Insertion:- Update the
prevandnextpointers ofnode1,node2, and their neighboring nodes to insertnode2beforenode1. -
Continue Iteration:- After each comparison and possible insertion, move
node1to the next position in the list. -
Completion:- Once the loop finishes, the list is sorted, and the function is done.