From 693245986123d58cd3848041205097f163580fa6 Mon Sep 17 00:00:00 2001 From: Tushar Sharma Date: Sun, 13 Jan 2019 21:57:16 +0530 Subject: [PATCH] Contribution added to Quicksort_Viz Suggest alter way for mousePressed() function. --- CC_QuickSort/QuickSort_Updated.pde | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 CC_QuickSort/QuickSort_Updated.pde diff --git a/CC_QuickSort/QuickSort_Updated.pde b/CC_QuickSort/QuickSort_Updated.pde new file mode 100644 index 0000000..bf323e7 --- /dev/null +++ b/CC_QuickSort/QuickSort_Updated.pde @@ -0,0 +1,57 @@ + +float[] values; + +int i, j; + +void setup() { + size(600, 400); + values = new float[width]; + for (int i = 0; i < values.length; i++) { + values[i] = random(height); + } +} + +void quicksort(float[] arr, int lo, int hi) { + if (lo < hi) { + int mid = partition(arr, lo, hi); + quicksort(arr, lo, mid-1); + quicksort(arr, mid+1, hi); + } +} + +void mousePressed() { + quicksort(values, 0, values.length-1); +} + +void draw() { + background(0); + for (int i = 0; i < values.length; i++) { + stroke(255); + line(i, height, i, height - values[i]); + } +} + +int partition (float arr[], int left, int right) +{ + float pivot = arr[right]; // pivot + i = left - 1; // Index of smaller element + + for(j = left; j <= right - 1; j++){ + if( arr[j] <= pivot){ + i++; + if(arr[i] != arr[j]){ + swap(arr, i, j); + break; + } + } + } + swap(arr, i+1, j); + return i+1; +} + +void swap(float[] arr, int a, int b) { + float temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + redraw(); +}