-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
44 lines (42 loc) · 1.32 KB
/
Copy pathQuickSort.java
File metadata and controls
44 lines (42 loc) · 1.32 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
import java.util.Scanner;
import java.util.Arrays;
public class QuickSort {
public static void main(String args[]) {
int i;
Scanner scan = new Scanner(System.in);
int size;
System.out.print("Enter the size:");
size = scan.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements:");
for (i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
sort(arr, 0, size - 1);
System.out.println("Sorted array: "+Arrays.toString(arr));
}
static void sort(int arr[], int start, int end) {
if (start < end) {
int pivotIndex = partition(arr, start, end);
sort(arr, start, pivotIndex - 1);
sort(arr, pivotIndex, end);
}
}
static int partition(int arr[], int start, int end) {
int pivot = arr[end];
int pivotIndex = start;
int temp;
for (int i = start; i < end; i++) {
if (arr[i] < pivot) {
temp = arr[i];
arr[i] = arr[pivotIndex];
arr[pivotIndex] = temp;
pivotIndex++;
}
}
temp = arr[pivotIndex];
arr[pivotIndex] = arr[end];
arr[end] = temp;
return pivotIndex;
}
}