forked from IamBisrutPyne/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
69 lines (58 loc) · 1.88 KB
/
QuickSort.java
File metadata and controls
69 lines (58 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class QuickSort {
/**
* Sorts an array using Quick Sort algorithm.
*
* @param arr The array to be sorted
* @param low Starting index
* @param high Ending index
*/
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
/**
* Partitions the array around a pivot element.
*
* @param arr The array to partition
* @param low Starting index
* @param high Ending index
* @return The index of the pivot after partition
*/
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // Choosing the last element as pivot
int i = low - 1; // Index of smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i+1] and pivot (arr[high])
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void main(String[] args) {
int[] sampleArray = { 10, 7, 8, 9, 1, 5 };
if (sampleArray == null || sampleArray.length == 0) {
System.out.println("Array is empty or null.");
return;
}
System.out.println("Original Array:");
for (int num : sampleArray) {
System.out.print(num + " ");
}
quickSort(sampleArray, 0, sampleArray.length - 1);
System.out.println("\n\nSorted Array:");
for (int num : sampleArray) {
System.out.print(num + " ");
}
}
}