Last active
February 1, 2020 15:05
-
-
Save jaideepheer/9e7213a8912d68b0da0bd2c95d4bb0bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.capability3; | |
import java.util.*; | |
public class binarysearch | |
{ | |
public static boolean search(int []arr,int n,int key) | |
{ | |
// Insert sort | |
int temp; | |
for(int i=0;i<n;i++) | |
{ | |
for(int j=0;j<n-i-1;j++) | |
{ | |
if(arr[i]>arr[j+1]) | |
{ | |
temp=arr[j+1]; | |
arr[j+1]=arr[i]; | |
arr[i]=temp; | |
} | |
} | |
} | |
// Binary search | |
int first=0; | |
int last=n-1; | |
int mid=(first+last)/2; | |
while(first<=last) | |
{ | |
if(arr[mid]<key) | |
{ | |
first=mid+1; | |
} | |
else if(arr[mid]==key) | |
{ | |
return true; | |
} | |
else | |
{ | |
last=mid-1; | |
} | |
mid=(first+last)/2; | |
} | |
return false; | |
} | |
public static void main(String args[]) | |
{ | |
Scanner in=new Scanner(System.in); | |
// Input array | |
System.out.println("Enter the size of array"); | |
int n = in.nextInt(); | |
int []arr = new int[n]; | |
for(int i=0;i<n;i++) | |
{ | |
System.out.println("Enter the array elements"); | |
arr[i]=in.nextInt(); | |
} | |
// Search element | |
System.out.println("Enter number to be searched"); | |
int key = in.nextInt(); | |
System.out.println(search(arr,n,key)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.capability3; | |
import java.util.*; | |
public class bubblesort | |
{ | |
public static int[] sort(int[]arr,int n) | |
{ | |
int temp = 0; | |
for(int i=0; i < n; i++){ | |
for(int j=1; j < (n-i); j++){ | |
if(arr[j-1] > arr[j]){ | |
temp = arr[j-1]; | |
arr[j-1] = arr[j]; | |
arr[j] = temp; | |
} | |
}}return arr; | |
} | |
public static void main(String args[]) | |
{ | |
Scanner in=new Scanner(System.in); | |
System.out.println("enter size of array"); | |
int n=in.nextInt(); | |
int[] arr=new int[n]; | |
for(int i=0;i<n;i++) | |
{ | |
System.out.println("Enter arrray elements");; | |
arr[i]=in.nextInt(); | |
} | |
sort(arr,n); | |
for(int i=0;i<n;i++) | |
{ | |
System.out.println(arr[i]); | |
}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment