all about C++ and PHP
import java.util.*; import java.util.concurrent.*; public class SortRace { /** * @param args * @developer lipun4u */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub int max = 10000; int array[] = new int[max]; Random randomGenerator = new Random(); for(int i=0; i<max; i++) array[i] = randomGenerator.nextInt(max*10); List<String> sortList = Collections.synchronizedList(new ArrayList<String>()); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch prepareLatch = new CountDownLatch(3); CountDownLatch endLatch = new CountDownLatch(3); new SortThread("BubbleSort", startLatch, prepareLatch, endLatch, array, sortList).start(); new SortThread("InsertionSort", startLatch, prepareLatch, endLatch, array, sortList).start(); new SortThread("SelectionSort", startLatch, prepareLatch, endLatch, array, sortList).start(); startLatch.countDown(); endLatch.await(); System.out.println("Fisrt Position : " + sortList.get(0)); System.out.println("Second Position : " + sortList.get(1)); System.out.println("Third Position : " + sortList.get(2)); } } class SortThread extends Thread { private String sortName; private CountDownLatch startLatch, prepareLatch, endLatch; private int[] pArray; private int[] array; List<String> list; public SortThread(String sortName, CountDownLatch startLatch, CountDownLatch prepareLatch, CountDownLatch endLatch, int[] pArray, List<String> list) { this.sortName = sortName; this.startLatch = startLatch; this.prepareLatch = prepareLatch; this.endLatch = endLatch; this.list = list; this.pArray = pArray; System.out.println(sortName + " Started.."); } public void run() { try { startLatch.await(); prepareArray(); prepareLatch.countDown(); prepareLatch.await(); if(sortName == "BubbleSort") { bubble_sort(array); } else if(sortName == "InsertionSort") { insertion_sort(array); } else if(sortName == "SelectionSort") { selection_sort(array); } list.add(sortName); endLatch.countDown(); } catch(Exception e) { e.printStackTrace(); } } public void prepareArray() { array = new int[pArray.length]; System.arraycopy(array,0, pArray, 0, pArray.length); } public void insertion_sort(int array[]) { for(int i=1; i<array.length; i++) { int j=i; int b = array[i]; while((j>0) && (array[j-1]>b)) { array[j] = array[j-1]; j--; } array[j] = b; } } public void bubble_sort(int array[]) { for(int i=0; i<array.length; i++) { for(int j=1; j<(array.length-i); j++) { if(array[j-1]>array[j]) { int t = array[j-1]; array[j-1]=array[j]; array[j]=t; } } } } public void selection_sort(int array[]) { for(int i=0; i<array.length; i++) { for(int j=i+1; j<array.length;j++) { if(array[i]>array[j]) { int t = array[i]; array[i]=array[j]; array[j]=t; } } } } }
No comments:
Post a Comment