C Programming : Let us learn a Sorting Technique

in hive-175254 •  2 years ago 

Good evening fellas ,
Are you guys ready to learn something new in C Programming today ? Today we will learn to sort elements of array. So do you know what is sorting ?

Let me give a short explanation to all of you about sorting. So sorting is a technique with the help of which we arrange the elements of array in order. Basically in Ascending or Descending order.

So let us see the program itself.

Screenshot 2023-01-19 201741.png

You can copy the same code from below :

#include <stdio.h>

void bubble_sort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

int main() {
int arr[] = {5, 1, 4, 2, 8};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Explanation of the program

The program starts with a function named bubble_sort that takes in two parameters. an array of integers named arr and an integer named n which is the size of the array.

It then uses a nested for loop structure, the outer loop iterates from 0 to n-1 and inner loop iterates from 0 to n-i-1.

The inner loop compares each pair of adjacent elements in the array and swaps them if the first element is greater than the second element. This process is repeated until the entire array is sorted.

nested for loop for sorting the array

image.png

After sorting the array, the program prints out the sorted array using a for loop.

Let us now look at the example.

Screenshot 2023-01-19 203120.png

image.png

So our program was able to sort the Array in ascending order as you can see in the above program.

Thank you

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

I will visit my laptop later so that I can really learn what you have teach us

you can follow up my previous post to learn more about C.