From bbec0ebacf0604c8ae6b05b15ca7d08e3cbf4137 Mon Sep 17 00:00:00 2001 From: Muhammed Sabah Date: Sat, 30 Jan 2021 17:57:31 +0530 Subject: [PATCH] Added QuickSort in java (#50) * added merge sort in java * Added QuickSort in java --- sorting/README.md | 1 + sorting/java/quick-sort.java | 81 ++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 sorting/java/quick-sort.java diff --git a/sorting/README.md b/sorting/README.md index b7ed7f81..84457784 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -26,6 +26,7 @@ 2. [Insertion Sort](java/insertion-sort.java) 3. [Selection Sort](java/selection-sort.java) 4. [Merge Sort](java/merge-sort.java) +5. [Quick Sort](java/quick-sort.java) ### JavaScript diff --git a/sorting/java/quick-sort.java b/sorting/java/quick-sort.java new file mode 100644 index 00000000..e61ac08b --- /dev/null +++ b/sorting/java/quick-sort.java @@ -0,0 +1,81 @@ +// Java program for implement Quick Sort +//Note: Rightmost element in the array is choosen as pivot +class QuickSortBack +{ + private int[] arr; + public QuickSortBack() + { + arr = new int[]{222,64,545,99,12,35,1,87,33,945,77}; // Array to be sorted + + } + + //Function to swap two Array elements + public void swap(int index1 , int index2) + { + int x = arr[index1]; //first value in temporary variable x + arr[index1] = arr[index2]; + arr[index2] = x; + + } + + //Function to print the Array + public void displayArray() + { + for (int i=0;i0 && arr[--rightptr]>pivot); //Find smaller item + + if (leftptr>=rightptr) //if index numbers cross,partition is done + break; + else + swap(leftptr,rightptr); //swap elements + + } + swap(leftptr,right); //restore pivot element + return leftptr; //return pivot location + } + + //Recursive quicksort function + public void recQuickSort(int left,int right) + { + if (right-left <= 0) // already sorted if size is 1 + return; + else + { + int pivot = arr[right]; //choosing pivot as rightmost(end) element of Array + int partition = partitionFn(left,right,pivot); + recQuickSort(left,partition-1); //Sort left + recQuickSort(partition+1,right); //Sort right + + } + } + + //function called in main + public void quickSort() + { + recQuickSort(0,arr.length-1); + } +} + +class QuickSort +{ + //Driver code to test above + public static void main(String[] args) { + + QuickSortBack ob = new QuickSortBack(); + ob.displayArray(); //display array before sort + ob.quickSort(); //call quickSort + ob.displayArray(); + } +} \ No newline at end of file