From 95de7e75714dbc737f9e304f250c64da0fe89b40 Mon Sep 17 00:00:00 2001 From: Suraj Subramanian Date: Mon, 28 Dec 2020 21:15:51 +0530 Subject: [PATCH] Multithreaded Quick Sort --- .../sorting/QuickSortMultiThreaded.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Threads/src/com/cdac/threads/sorting/QuickSortMultiThreaded.java diff --git a/Threads/src/com/cdac/threads/sorting/QuickSortMultiThreaded.java b/Threads/src/com/cdac/threads/sorting/QuickSortMultiThreaded.java new file mode 100644 index 0000000..c6d2933 --- /dev/null +++ b/Threads/src/com/cdac/threads/sorting/QuickSortMultiThreaded.java @@ -0,0 +1,87 @@ +package com.cdac.threads.sorting; +/* + * Author: Suraj Subramanian + * + * Quick Sort implemented using Generics and Multithreading + * + * */ + +public class QuickSortMultiThreaded> implements Runnable { + + private T arr[]; + private int start; + private int end; + + // Driver + public static void main(String[] args) { + Integer[] data = { 5, 10, 4, 1, 2, 88, 11, 23, 13 }; + new QuickSortMultiThreaded().quickSort(data); + + for (Integer integer : data) { + System.out.println(integer); + } + } + + private int partition(T arr[], int start, int end) { + // set pivot as last element + T pivot = arr[end]; + int index = start - 1; + + for (int i = start; i <= end - 1; i++) { + if (arr[i].compareTo(pivot) < 0) { + index++; + T temp = arr[index]; + arr[index] = arr[i]; + arr[i] = temp; + } + } + + T temp = arr[index + 1]; + arr[index + 1] = arr[end]; + arr[end] = temp; + + return index + 1; + } + + private void quickSort(T arr[]) { + Thread t = new Thread(new QuickSortMultiThreaded(arr, 0, arr.length - 1)); + t.start(); + try { + t.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public QuickSortMultiThreaded(T arr[], int start, int end) { + super(); + this.arr = arr; + this.start = start; + this.end = end; + } + + public QuickSortMultiThreaded() { + super(); + } + + @Override + public void run() { + if (start < end) { + // partition the array + int partition = partition(arr, start, end); + + Thread t1 = new Thread(new QuickSortMultiThreaded(arr, start, partition - 1)); + Thread t2 = new Thread(new QuickSortMultiThreaded(arr, partition + 1, end)); + + t1.start(); + t2.start(); + + try { + t1.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + +} \ No newline at end of file