Showing posts with label DSA. Show all posts
Showing posts with label DSA. Show all posts

Thursday, March 12, 2026

Bubble Sort Algorithm

Bubble Sort Algorithm

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. It continues this process until the array becomes sorted.

Algorithm



void bubbleSort(int arr[], int n){

int i, j, temp;

for(i = 0; i < n-1; i++){

    for(j = 0; j < n-i-1; j++){

        if(arr[j] > arr[j+1]){

            temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;

        }

    }

}

}

Binary Search Algorithm

Binary Search Algorithm

Binary Search works on sorted arrays.

Algorithm



int binarySearch(int arr[], int n, int key){
int low = 0;
int high = n-1;

while(low <= high){

int mid = (low+high)/2;

if(arr[mid]==key)
return mid;

else if(arr[mid] < key)
low = mid+1;

else
high = mid-1;
}

return -1;
}