Binary Search in Server Side and Client Side

Binary Search in Server Side and Client Side Server Side: import java.net.*; import java.io.*; import java.util.*; public class ServerBinSearch { public static void main(String[] arg) throws Exception { ServerSocket ss = new ServerSocket(8500); Socket s = ss.accept(); System.out.println("Connection OK"); DataInputStream din = new DataInputStream(s.getInputStream()); DataOutputStream dout = new DataOutputStream(s.getOutputStream()); int a[]; int n; n = Integer.parseInt(din.readUTF()); System.out.println("Got Size As: " + n); a = new int[n]; for(int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(din.readUTF()); System.out.println("Getting Value As: " + a[i]); } int key = Integer.parseInt(din.readUTF()); System.out.println("Got Key As: " + key); int flag = binSearch(a, n, 0, a.length-1, key); dout.writeUTF("" + flag); ss.close(); s.close(); } public static int binSearch(int a[], int n, int low, int high, int key) { while(low <= high) { int mid = (low+high)/2; if (a[mid] == key) { return 1; } else if (key > a[mid]) { low = mid + 1; } else { high = mid - 1; } } return 0; } } Client Side: import java.io.*; import java.net.*; import java.util.*; public class ClientBinSearch { public static void main(String[] args) throws Exception { int a[]; int n = 0; System.out.println("Enter The Size Of The Array: "); Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = sc.nextInt(); } Socket s = new Socket("localhost", 8500); DataInputStream din = new DataInputStream(s.getInputStream()); DataOutputStream dout = new DataOutputStream(s.getOutputStream()); dout.writeUTF("" + n); for (int i = 0; i < a.length; i++) { dout.writeUTF("" + a[i]); } System.out.println("Find Key? :"); int key = sc.nextInt(); dout.writeUTF("" + key); String found = din.readUTF(); if (found.equals("1")) { System.out.println("Found!"); } else { System.out.println("Not Found!"); } s.close(); } }

Share:

0 comments