728x90

 

1. Linear Search Algorithm: Linear search is a basic searching algorithm that searches for a target value in an array by iterating over each element of the array one by one.

int linearSearch(int arr[], int n, int x) {
   int i;
   for (i = 0; i < n; i++) {
      if (arr[i] == x) 
         return i; //return the index of the found value
   }
   return -1; //if value is not found, return -1
}
 
 

2. Bubble Sort Algorithm: Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.

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;
         }
      }
   }
}
 

3. Factorial Algorithm: Factorial is a mathematical function that multiplies a given number with all the natural numbers below it. This algorithm calculates the factorial of a given number using recursion.

int factorial(int n) {
   if (n == 0) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}
 

4. Binary Search Algorithm: Binary search is a fast searching algorithm with time complexity O(log n). It searches for a target value in a sorted array by repeatedly dividing the search interval in half.

int binarySearch(int arr[], int l, int r, int x) {
   if (r >= l) {
      int mid = l + (r - l) / 2;
      if (arr[mid] == x)
         return mid;
      if (arr[mid] > x)
         return binarySearch(arr, l, mid - 1, x);
      return binarySearch(arr, mid + 1, r, x);
   }
   return -1; //if value is not found, return -1
}
 

 

728x90

+ Recent posts