diff --git a/Binary search.java b/Binary search.java new file mode 100644 index 0000000..91c9e28 --- /dev/null +++ b/Binary search.java @@ -0,0 +1,39 @@ +import java.util.*; +class Binarysearch { +public static void main(String[] args) +{ + int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100}; + int item, location = -1; + System.out.println("Enter the item which you want to search"); + Scanner sc = new Scanner(System.in); + n = sc.nextInt(); + address = binarySearch(arr,0,9,item); + if(address != -1) + System.out.println("the location of the item is "+location); + else + System.out.println("Item not found"); + } + +public static int binarySearch(int[] a, int beg, int end, int n) +{ + int mid; + if(end >= beg) + { + mid = (beg + end)/2; + if(a[mid] == n) + { + return mid+1; + } + else if(a[mid] < n) + { + return binarySearch(a,mid+1,end,n); + } + else + { + return binarySearch(a,beg,mid-1,n); + } + + } + return -1; +} +} diff --git a/heap Sort.java b/heap Sort.java new file mode 100644 index 0000000..03394b7 --- /dev/null +++ b/heap Sort.java @@ -0,0 +1,68 @@ +/*A heap is a tree with some special properties, so value of node should be greater +than or equal to(less than or equal to in case of min heap) children of the node and +tree should be complete binary tree */ + +import java.util.*; + +public class HeapSortMain { + + public static void buildheap(int []arr) { + + /* + * As last non leaf node will be at (arr.length-1)/2 + * so we will start from this location for heapifying the elements + * */ + for(int i=(arr.length-1)/2; i>=0; i--){ + heapify(arr,i,arr.length-1); + } + } + + public static void heapify(int[] arr, int i,int size) { + int left = 2*i+1; + int right = 2*i+2; + int max; + if(left <= size && arr[left] > arr[i]){ + max=left; + } else { + max=i; + } + + if(right <= size && arr[right] > arr[max]) { + max=right; + } + // If max is not current node, exchange it with max of left and right child + if(max!=i) { + exchange(arr,i, max); + heapify(arr, max,size); + } + } + + public static void exchange(int[] arr,int i, int j) { + int t = arr[i]; + arr[i] = arr[j]; + arr[j] = t; + } + + public static int[] heapSort(int[] arr) { + + buildheap(arr); + int sizeOfHeap=arr.length-1; + for(int i=sizeOfHeap; i>0; i--) { + exchange(arr,0, i); + sizeOfHeap=sizeOfHeap-1; + heapify(arr, 0,sizeOfHeap); + } + return arr; + } + + public static void main(String[] args) { + int[] arr={1,10,16,19,3,5}; + System.out.println("Before Heap Sort : "); + System.out.println(Arrays.toString(arr)); + arr=heapSort(arr); + System.out.println("====================="); + System.out.println("After Heap Sort : "); + System.out.println(Arrays.toString(arr)); + } +} + \ No newline at end of file