diff --git a/basic_algo/bubbleSort.cpp b/basic_algo/bubbleSort.cpp new file mode 100644 index 0000000..6c0e620 --- /dev/null +++ b/basic_algo/bubbleSort.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +void printArray(int *arr, int length) +{ + for (int i = 0; i < length; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} + +void bubbleSort(int *arr, int length) +{ + for (int i = 0; i < length - 1; i++) + { + for (int j = 0; j < length - 1 - i; j++) + { + if (arr[j] > arr[j + 1]) + { + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +void bubbleSortAdaptive(int *arr, int length) +{ + int isSorted = 0; + for (int i = 0; i < length - 1; i++) + { + isSorted = 1; + for (int j = 0; j < length - 1 - i; j++) + { + if (arr[j] > arr[j + 1]) + { + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + isSorted = 0; + } + } + if (isSorted) + { + return; + } + } +} + +int main() +{ + int arr[] = {12, 54, 65, 7, 23, 9}; + int length = sizeof(arr) / sizeof(int); + printArray(arr, length); + bubbleSortAdaptive(arr, length); + printArray(arr, length); + + return 0; +} diff --git a/searching/binary-search.cpp b/searching/binary-search.cpp new file mode 100644 index 0000000..deeec4e --- /dev/null +++ b/searching/binary-search.cpp @@ -0,0 +1,37 @@ +// Implementing binary search in C++ + +#include +using namespace std; + +int binarySearch(int arr[], int size, int element){ + int low, mid, high; + low = 0; + high = size -1; + while(low<=high){ + mid = (low + high)/2; + if(arr[mid]==element){ + return mid; + } + if(arr[mid]>element; + + int index = binarySearch(arr, size, element); + cout<<"The element "< +using namespace std; + +int linearSearch(int arr[], int size, int element){ + for (int i = 0; i < size; i++) + { + if(arr[i]==element){ + return i; + } + } + return -1; +} + +int main() +{ + int arr[] = {12,21,32,41,52, 63, 76, 54, 23, 54, 27}; + int size = sizeof(arr)/sizeof(int); + int element; + cout<<"Enter the element you want to search : "; + cin>>element; + + int index = linearSearch(arr, size, element); + cout<<"The element "<