Skip to content

Commit e9b1e25

Browse files
authored
Updated QuickSort.java
Updated quicksort to its generic version and changed the filename according to convention
1 parent a009cca commit e9b1e25

File tree

2 files changed

+93
-102
lines changed

2 files changed

+93
-102
lines changed

Sorts/QuickSort.java

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/**
2+
*
3+
* @author Varun Upadhyay (https://github.com/varunu28)
4+
*
5+
*/
6+
7+
class QuickSort {
8+
9+
/**
10+
* This method implements the Generic Quick Sort
11+
*
12+
* @param array The array to be sorted
13+
* @param start The first index of an array
14+
* @param end The last index of an array
15+
* Sorts the array in increasing order
16+
**/
17+
18+
public static <T extends Comparable<T>> void QS(T array[], int start, int end) {
19+
if (start < end) {
20+
int PIndex = partition(array, start, end);
21+
QS(array, start, PIndex - 1);
22+
QS(array, PIndex + 1, end);
23+
}
24+
}
25+
26+
/**
27+
* This method finds the partition index for an array
28+
*
29+
* @param array The array to be sorted
30+
* @param start The first index of an array
31+
* @param end The last index of an array
32+
* Finds the partition index of an array
33+
**/
34+
35+
public static <T extends Comparable<T>> int partition(T array[], int start, int end) {
36+
T pivot = array[end];
37+
int PIndex = start;
38+
for (int i=start;i<end;i++) {
39+
if (array[i].compareTo(pivot) <= 0) {
40+
swap(array, i, PIndex);
41+
PIndex++;
42+
}
43+
}
44+
swap(array, PIndex, end);
45+
return PIndex;
46+
}
47+
48+
/**
49+
* This method swaps two elements of an array
50+
*
51+
* @param array The array to be sorted
52+
* @param initial The first element
53+
* @param fin The second element
54+
* Swaps initial and fin element
55+
**/
56+
57+
public static <T extends Comparable<T>> void swap(T[] array, int initial, int fin) {
58+
T temp = array[initial];
59+
array[initial] = array[fin];
60+
array[fin] = temp;
61+
}
62+
63+
// Driver Program
64+
public static void main(String[] args) {
65+
66+
// For integer input
67+
int[] arr = {3,4,1,32,0,2,44,111,5};
68+
Integer[] array = new Integer[arr.length];
69+
for (int i=0;i<arr.length;i++) {
70+
array[i] = arr[i];
71+
}
72+
73+
QS(array, 0, arr.length-1);
74+
75+
//Output => 0 1 2 3 4 5 32 44 111
76+
for (int i=0;i<array.length;i++) {
77+
System.out.print(array[i] + " ");
78+
}
79+
System.out.println();
80+
81+
// String Input
82+
String[] array1 = {"c", "a", "e", "b","d"};
83+
84+
QS(array1, 0,array1.length-1);
85+
86+
//Output => a b c d e
87+
for(int i=0; i<array1.length; i++)
88+
{
89+
System.out.print(array1[i]+"\t");
90+
}
91+
}
92+
}
93+

Sorts/Quicksort.java

Lines changed: 0 additions & 102 deletions
This file was deleted.

0 commit comments

Comments
 (0)