Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Binary search.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
68 changes: 68 additions & 0 deletions heap Sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*A heap is a tree with some special properties, so value of node should be greater
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a folder called Sort and then add this file in it.

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));
}
}