Untitled
unknown
plain_text
3 years ago
2.3 kB
15
Indexable
import java.util.Scanner;
//node class represent node in bst class Node{
int key;
Node left,right,p; public Node(int x){
this.key=x;
this.left=null;
this.right=null;
this.p=null;
}
}
//bst class class BST{
//root ro bst
Node root; //constructor that intialize the root of bst
static int couter=0;
BST (int key){
this.root=new Node(key);
} //insertion method public void insert(Node root,int key){
couter++;
if(root.key>key){
if(root.left!=null){ insert(root.left,key); }
else{
root.left=new Node(key); root.left.p=root;
}
Step 2/3
}
else{
if(root.right!=null){ insert(root.right,key);
} else{
root.right=new Node(key); root.right.p=root;
}
}
}
//inorder traversal method for output the sorted array public void inorder(Node root){ if(root==null){
return;
} inorder(root.left); System.out.print(root.key+" "); inorder(root.right);
} 11 }
public class Main
//scanner for taking input
{ public static Scanner sc=new Scanner(System.in); public static void main(String[] args) { System.out.print("Enter Size of the
int n=0;
Array: ");
n=sc.nextInt(); int array[]=new int[n]; for(int i=0 i<n;i++){
Step 3/3
//scanner for taking input public static Scanner sc=new Scanner(System.in); public static void main(String[] args) {
int n=0; System.out.print("Enter Size of the
Array: ");
n=sc.nextInt(); int array[]=new int[n]; for(int i=0;i<n;i++){ System.out.print("Enter "+(i+1)+" element of array: "); array[i]=sc.nextInt(); }
//creating bst object and inserting all element of array in bst BST mytree=new BST (array[0]); for(int i=1;i<n;i++){ mytree.insert(mytree.root,array[i]); }
//output
System.out.println("\nSize of the array : "+n); System.out.print("Input array: ");
for(int i=0;i<n;i++){ System.out.print(array[i]+" ");
}
System.out.print("\nSorted Array: "); mytree.inorder(mytree.root); System.out.print("\nNumber of key comparison: "+mytree.couter); }
}
Explanation for step 3
If you have any doubt then comment
Final answer
Output
Enter Size of the Array : 4 Enter 1 element of array: 6
Enter 2 element of array: 2
Enter 3 element of array: 8
Enter 4 element of array: 5
Size of the array: 4
Input array: 6 2 8 5
Sorted Array: 2 5 6 8
Number of key comparison : 4
...Program finished with exit Press ENTER to exit console.Editor is loading...