diff --git a/Algorithms/Searching Algorithms/Binary_Search.md b/Algorithms/Searching Algorithms/Binary_Search.md index 334e088..072e7ea 100644 --- a/Algorithms/Searching Algorithms/Binary_Search.md +++ b/Algorithms/Searching Algorithms/Binary_Search.md @@ -100,6 +100,40 @@ static int binarySearch(int[] arr, int target) { //Declaring the binary search f return 0; //when target not found return 0 } ``` + + +### Code `C++` +``` c++ +#include +using namespace std; +int binarySearch(int arr[],int left, int right,int x){ + if(r>=l) + { + int mid=left+(right-left)/2; + if(arr[mid]==x){ + return mid; + } + if(arr[mid]>x){ + return binarySearch(arr, mid+1,right,x); + } + if(arr[mid]Note: The while loop runs until the value of start index is less than equal to the end index. When start=end at that time mid=start=end thus arr[mid] >is the target. After that start>end which breaks the while loop. diff --git a/Algorithms/Sorting Algorithms/Selection_sort.md b/Algorithms/Sorting Algorithms/Selection_sort.md index a1c04dd..44f4119 100644 --- a/Algorithms/Sorting Algorithms/Selection_sort.md +++ b/Algorithms/Sorting Algorithms/Selection_sort.md @@ -44,8 +44,8 @@ Step 5 - Repeat until array is sorted. Here we can observe that for 6 elements we need 5 pass(iterations) so, for n elements (n-1) passes are required. -## Code: - +## C++ Code: +``` cpp #include #include @@ -84,6 +84,45 @@ Here we can observe that for 6 elements we need 5 pass(iterations) so, for n ele printf("\n"); return 0; } + ``` + + ## Java Code: + ```java +public class selectionSort { +void sort(int arr[]) +{ + int n = arr.length; + for (int i = 0; i < n-1; i++) + { + int min= i; + for (int j = i+1; j < n; j++) + if (arr[j] < arr[min]) + min= j; + + int temp = arr[min]; + arr[min] = arr[i]; + arr[i] = temp; + } +} + +void display(int arr[]) +{ + int n = arr.length; + for (int i=0; i arr[midIndex] ) + left = midIndex + 1 + else + right = midIndex - 1 +``` +## C++ Code +``` cpp +#include +using namespace std; +int binarySearch(int arr[],int left, int right,int x){ + if(right>=l) + { + int mid=left+(right-l)/2; + if(arr[mid]==x){ + return mid; + } + if(arr[mid]>x){ + return binarySearch(arr, mid+1,right,x); + } + if(arr[mid]