fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. ArrayList <Integer> array = new ArrayList(Arrays.asList(new Integer[]{
  8. 4, 27, 0, 0, 25, 29, 9, 27, 1, 29, 12, 2, 23, 22, 0,
  9. 19, 17, 2, 22, 24, 21, 27, 6, 6, 7, 4, 20, 7, 26, 10
  10. }));
  11. QuickSortWithThreads obj = new QuickSortWithThreads(array,0 ,array.size()-1 );
  12.  
  13. for(int i=0; i<array.size();i++)
  14. System.out.println(array.get(i));
  15.  
  16. }
  17. }
  18.  
  19.  
  20. class QuickSortWithThreads {
  21.  
  22. public QuickSortWithThreads(ArrayList <Integer> arr, int left, int right){
  23. quicksort(arr,left,right);
  24.  
  25. }
  26.  
  27. static void quicksort(ArrayList <Integer> arr, int left, int right) {
  28. int pivot;
  29.  
  30. if(left<right){
  31. pivot = partition(arr,left,right);
  32. QuickSortThread threadLeftSide = new QuickSortThread(arr,pivot+1,right);
  33. threadLeftSide.start();
  34. quicksort(arr,left,pivot-1);
  35. try {
  36. threadLeftSide.join();
  37. } catch (InterruptedException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41.  
  42. }
  43.  
  44. }
  45.  
  46. static int partition(ArrayList <Integer> arr, int left, int right)
  47. {
  48.  
  49. int pivot = arr.get(right);
  50. int i = left -1;
  51. for( int j=left; j<=right-1;j++){
  52. if (arr.get(j)<=pivot){
  53. i=i+1;
  54. exchange(arr,i,j);
  55. }
  56. }
  57. exchange(arr,i+1,right);
  58.  
  59. return i+1;
  60. }
  61. static void exchange(ArrayList<Integer> arr, int i,int j){
  62. int swap = arr.get(i);
  63. arr.set(i,arr.get(j));
  64. arr.set(j, swap);
  65. }
  66.  
  67. private static class QuickSortThread extends Thread {
  68. int right;
  69. int left;
  70. ArrayList<Integer> refArray;
  71.  
  72. public QuickSortThread(ArrayList<Integer> array,int left,int right) {
  73. this.right = right;
  74. this.left=left;
  75. refArray = new ArrayList<Integer>();
  76. refArray=array;
  77.  
  78. }
  79.  
  80. public void run() {
  81. quicksort(refArray,left,right);
  82.  
  83.  
  84. }
  85. }}
Success #stdin #stdout #stderr 0.07s 382528KB
stdin
Standard input is empty
stdout
0
0
0
1
2
2
4
4
6
6
7
7
9
10
19
17
22
21
12
20
22
27
25
29
27
29
24
23
26
27
stderr
Exception in thread "Thread-0" java.lang.OutOfMemoryError: unable to create new native thread
	at java.lang.Thread.start0(Native Method)
	at java.lang.Thread.start(Thread.java:691)
	at QuickSortWithThreads.quicksort(Main.java:33)
	at QuickSortWithThreads$QuickSortThread.run(Main.java:81)
Exception in thread "Thread-6" java.lang.OutOfMemoryError: unable to create new native thread
	at java.lang.Thread.start0(Native Method)
	at java.lang.Thread.start(Thread.java:691)
	at QuickSortWithThreads.quicksort(Main.java:33)
	at QuickSortWithThreads$QuickSortThread.run(Main.java:81)