From 51ba9ab6b8d204cf974bedb6cbb2b87eab3d22f6 Mon Sep 17 00:00:00 2001 From: name <31079868+yyds5@users.noreply.github.com> Date: Thu, 14 Oct 2021 11:25:54 -0400 Subject: [PATCH 1/2] add sleep sort in java add sleep sort in java --- Sorting Algorithms/Java/SleepSort.java | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Sorting Algorithms/Java/SleepSort.java diff --git a/Sorting Algorithms/Java/SleepSort.java b/Sorting Algorithms/Java/SleepSort.java new file mode 100644 index 00000000..7d61d065 --- /dev/null +++ b/Sorting Algorithms/Java/SleepSort.java @@ -0,0 +1,28 @@ +import java.util.concurrent.CountDownLatch; + +public class SleepSort { + private static Thread Tread; + + public static void main(String[] args) { + int[] nums = {0,1,2,3,4}; + sleepSort(nums); + } + + public static void sleepSort(int[] nums){ + CountDownLatch completeSignal = new CountDownLatch(nums.length); + for(int num : nums){ + new Thread(() -> { + completeSignal.countDown(); + try{ + //in order to make the sort more visible in console, + // factor of 1000 milliseconds is used. + completeSignal.await(); + Tread.sleep(num * 1000); + System.out.println(num); + }catch(InterruptedException e){ + e.printStackTrace(); + } + }).start(); + } + } +} From 4d1573ef7fddded9e456e181a56d15e5751ba342 Mon Sep 17 00:00:00 2001 From: name <31079868+yyds5@users.noreply.github.com> Date: Thu, 14 Oct 2021 20:10:53 -0400 Subject: [PATCH 2/2] Update SleepSort.java add comment --- Sorting Algorithms/Java/SleepSort.java | 32 +++++++++++++++++--------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/Sorting Algorithms/Java/SleepSort.java b/Sorting Algorithms/Java/SleepSort.java index 7d61d065..4f90e32c 100644 --- a/Sorting Algorithms/Java/SleepSort.java +++ b/Sorting Algorithms/Java/SleepSort.java @@ -1,6 +1,10 @@ +import java.util.ArrayList; import java.util.concurrent.CountDownLatch; public class SleepSort { + //Sleep sort puts each element of an integer array into sleep at the same time + // due to the value differences, the smaller value would "wake up" first hence added to + // the array first and so on. private static Thread Tread; public static void main(String[] args) { @@ -10,17 +14,23 @@ public static void main(String[] args) { public static void sleepSort(int[] nums){ CountDownLatch completeSignal = new CountDownLatch(nums.length); - for(int num : nums){ - new Thread(() -> { - completeSignal.countDown(); - try{ - //in order to make the sort more visible in console, - // factor of 1000 milliseconds is used. - completeSignal.await(); - Tread.sleep(num * 1000); - System.out.println(num); - }catch(InterruptedException e){ - e.printStackTrace(); + ArrayList sortedNums = new ArrayList<>(); + for(int i = 0; i