Created
September 28, 2016 17:58
-
-
Save sid24rane/06820e3557adfbe87b314f46800d7129 to your computer and use it in GitHub Desktop.
Searching and sorting algorithms operations - Mutithreading in Java
This file contains hidden or 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 Multithreading; | |
import java.util.Scanner; | |
class MyThread extends Thread{ | |
private int[] arr; | |
MyThread(int[] arr){ | |
this.arr = arr; | |
} | |
// 8 4 2 | |
public void run(){ | |
System.out.println("(From child thread) :=> Starting sorting process!"); | |
// selection sort | |
for(int i=0;i<arr.length-1;i++){ | |
int min = i; | |
for(int k=i+1;k<arr.length;k++){ | |
if(arr[k]<arr[min]){ | |
min = k; | |
} | |
} | |
int temp = arr[min]; | |
arr[min]= arr[i]; | |
arr[i]=temp; | |
} | |
System.out.println("(From child thread) :=> Done sorting"); | |
} | |
} | |
class Search extends Thread{ | |
private int[] arr; | |
private int val; | |
Search(int[] a,int val){ | |
this.arr = a; | |
this.val = val; | |
} | |
public void run(){ | |
System.out.println("(From child thread) :=> Starting searching process!"); | |
// binary search | |
int low = 0; | |
int high = arr.length-1; | |
while(low<=high){ | |
int mid = (low+high)/2; | |
if(arr[mid] == val){ | |
System.out.println("Element found at index :" + mid); | |
return; | |
}else if(arr[mid] > val){ | |
high = mid - 1; | |
}else{ | |
low = mid + 1; | |
} | |
} | |
System.out.println("Element not found!"); | |
System.out.println("(From child thread) :=> Done searching"); | |
} | |
} | |
public class MultiThreading { | |
// helper method to print arr elements | |
public static void display(int[] a){ | |
for(int i=0;i<a.length;i++){ | |
System.out.println(a[i]); | |
} | |
} | |
public static void main(String[] args) throws InterruptedException{ | |
Scanner s = new Scanner(System.in); | |
System.out.println("Enter number of integers u want to sort :"); | |
int n = s.nextInt(); | |
int[] arr = new int[n]; | |
// user input | |
for(int i=0;i<n;i++){ | |
arr[i]=s.nextInt(); | |
} | |
System.out.println("Entered numbers are :"); | |
display(arr); | |
// creating child thread | |
MyThread m = new MyThread(arr); | |
m.start(); | |
// waiting for child thread to complete | |
m.join(); | |
System.out.println("Sorted numbers are :"); | |
display(arr); | |
System.out.println("Enter number to search:"); | |
int value = s.nextInt(); | |
Search ns = new Search(arr,value); | |
ns.start(); | |
// waiting for child thread to complete | |
ns.join(); | |
System.out.println("Exiting main thread!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment