Algorithms

Searching Algorithms :

		

Linear search (Time complexity): O(n)

#include<iostream> using namespace std; void linear_search(int *arr,int n,int element) { int counter = 0,i; for( i = 0 ; i < n ; i++) { if(element == arr[i]) { cout<<"Element is found at "<<counter+1<<"th position"<<endl; break; } counter++; } if(i == n) { cout<<"Element not found"<<endl; } } int main() { int n; cout<<"Enter the size of array : "; cin>>n; int arr[n]; cout<<"\nEnter the element of array : "<<endl; for(int i = 0 ; i < n ; i++) { cin>>arr[i]; } int element; cout<<"\nEnter the element you want to find : "; cin>>element; linear_search(arr,n,element); return 0; }
		

Binary search (Time complexity): O(log n)

#include<iostream> #include<algorithm> using namespace std; int Binary_search(int *arr,int left,int right,int element) { int middle; if(right >= left) { middle = (left + right)/2; if(arr[middle] == element) { return middle+1; } else if(arr[middle] < element) { return Binary_search(arr,middle+1,right,element); } else { return Binary_search(arr,left,middle-1,element); } } return -1; } int main() { int n; cout<<"Enter the size of array : "; cin>>n; int arr[n]; cout<<"\nEnter the element of array : "; for(int i = 0 ; i < n ; i++) { cin>>arr[i]; } sort(arr,arr+n); int element; cout<<"\nEnter the element you want to find : "; cin>>element; cout<<"\nSorted array : "; for(int i = 0 ; i < n ; i++) { cout<<arr[i]<<" "; } int position = -1; position = Binary_search(arr,0,n,element); cout<<endl; if(position != -1) { cout<<"\nIn sorted array Element found at "<<position<<"th place"<<endl; } else { cout<<"\nElement not found"<<endl; } return 0; }

Sorting Algorithms :

    

Bubble sort (Time complexity): O(n2)

#include <iostream> using namespace std; void swap_arr(int *no1, int *no2) { *no1 = *no1 + *no2; *no2 = *no1 - *no2; *no1 = *no1 - *no2; } void bubbleSort(int *arr, int n) { int i, j; for (i = 0; i < n-1; i++) { for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { swap_arr(&arr[j], &arr[j+1]); } } } } void printArray(int *arr, int n) { int i; for (i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; } int main() { int n; cout<<"Enter the size of the array : "; cin>>n; int arr[n]; cout<<"\nEnter the elements of the array : "; for(int i = 0 ;i < n ;i++) { cin>>arr[i]; } cout<<"\nBefore sort : "; printArray(arr, n); bubbleSort(arr, n); cout<<"\nAfter sort: "; printArray(arr, n); return 0; }

More comming soon!