Bubble sort Algorithm (c lang)

 By: Himanshu Tiwari 



In Bubble Sort algorithm, 

1 . traverse from left and compare adjacent elements and the higher one is placed at right side. 

2 . In this way, the largest element is moved to the rightmost end at first. 

3 . This process is then continued to find the second largest and place it and so on until the data is sorted.

#include<stdio.h>
void printarr(int arr[], int n){
    for(int i=0; i<n; i++){
        printf("%d ",arr[i]);
    }
    printf("\n");
}
void bubblesot(int arr[],int n){// or write int* arr;
    for(int i=0; i<n-1; i++){
        for(int j=0; j<n-1-i; j++){
            if(arr[j]>arr[j+1]){
            int temp=arr[j];
            arr[j]=arr[j+1];
            arr[j+1]=temp;
           
        }
    }
 
}
}
int main(){
int n;
printf("enter the size of the array : ");
scanf("%d",&n);
int arr[n];
printf("enter the elements of the array : ");
for(int i=0; i<n; i++){
    scanf("%d",&arr[i]);
}
printarr(arr,n);
bubblesot(arr,n);
printarr(arr,n);

    return 0;
}

Advantages of Bubble Sort:

Bubble sort is easy to understand and implement.

It does not require any additional memory space.

It is a stable sorting algorithm, meaning that elements with the same key value maintain their relative order in the sorted output.

Comments

Post a Comment

Popular Posts