Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

BINARY SEARCH

.
.
.
.
.
int binarySearch(int *input, int n, int val)
{
//Write your code here
int start=0,end=n-1;
int mid;
while(end>=start)
{
mid = (start + end) / 2;
if (val == input[mid]) {
return mid;
}
else if(val>input[mid] ){
start=mid+1;

}
else if(val<input[mid])
{
end=mid-1;

} else {
return 0;
}
}
return -1;
}

SELECTION SORT
.
.
.
.
.

#include <iostream>
using namespace std;
void print(int k[] , int a)
{
for(int i=0;i<a;i++)
{
cout<<k[i]<<" ";
}
}

void selectionsort(int arr[] , int size )


{
for (int i=0;i<size-1;i++)
{
int temp=0;
int c=i;
int min=arr[i];
for(int j=i+1;j<size;j++)
{
if(min>arr[j])
{
min=arr[j];
c=j;
}
}
temp=arr[i];
arr[i]=arr[c];
arr[c]= temp;
}
cout<<endl;
cout<<endl;
print(arr,size);
}
int main() {
// Write C++ code here
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
selectionsort(a,n);
return 0;

.
.
.
..
.
.
.

.
.

BUBBLE SORT
.
.
.
.
.
.
.
.
void bubbleSort(int *input, int size)
{
//Write your code here
for (int step = 0; step < (size - 1); ++step) {

// check if swapping occurs


int swapped = 0;
// loop to compare two elements
for (int i = 0; i < (size - step - 1); ++i) {

// compare two array elements


// change > to < to sort in descending order
if (input[i] > input[i + 1]) {

// swapping occurs if elements


// are not in intended order
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;

swapped = 1;
}
}

// no swapping means the array is already sorted


// so no need of further comparison
if (swapped == 0)
break;
}
}

You might also like