Menu
Coddy logo textTech

Swap adjacent elements

Lesson 3 of 11 in Coddy's Bubble Sort course.

We have discussed, how bubble sort works. We have to iterate through the list and swap elements who are in the wrong order. We have to repeat the process until the list becomes sorted.

Let's once again revise how a pass works: We have to iterate through the list, compare and swap adjacent elements.

We have to sort a list with 4 elements: [3,4,2,1]

Compares first two elements

[3,4,2,1] -> [3,4,2,1]     (No change, as they are already sorted)

Compares next two elements

[3,4,2,1] -> [3,2,4,1]    (Swaps the elements to make them in sorted order)

Compares next two elements

[3,2,4,1] -> [3,2,1,4]  (Swaps the elements to make them in sorted order)

In the last challenge, we have learned how to swap two elements. Here's a challenge for you to implement the above discussed process.

challenge icon

Challenge

Easy

Create a function named swap_list that receives an array. Iterate through the array, compare and swap adjacent elements and return the new list.

Try it yourself

#include <stdio.h>
#include <stdlib.h>

int* swap_list(int* arr, int arr_size, int* returnSize) {
    // Write code here
    *returnSize = arr_size;
    return arr;
}

All lessons in Bubble Sort