Skip to content

Commit e6b85e4

Browse files
authored
Merge pull request kothariji#473 from 24shreya/master
Added java quick sort algorithm
2 parents c398a5f + b7a5c8e commit e6b85e4

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Sorting/JAVA quick_sort.java

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
class QuickSort
3+
{
4+
5+
int partition(int arr[], int low, int high)
6+
{
7+
int pivot = arr[high];
8+
int i = (low-1);
9+
for (int j=low; j<high; j++)
10+
{
11+
12+
if (arr[j] <= pivot)
13+
{
14+
i++;
15+
16+
// swap arr[i] and arr[j]
17+
int temp = arr[i];
18+
arr[i] = arr[j];
19+
arr[j] = temp;
20+
}
21+
}
22+
23+
// swap arr[i+1] and arr[high] (or pivot)
24+
int temp = arr[i+1];
25+
arr[i+1] = arr[high];
26+
arr[high] = temp;
27+
28+
return i+1;
29+
}
30+
31+
32+
void sort(int arr[], int low, int high)
33+
{
34+
if (low < high)
35+
{
36+
37+
int pi = partition(arr, low, high);
38+
39+
sort(arr, low, pi-1);
40+
sort(arr, pi+1, high);
41+
}
42+
}
43+
44+
static void printArray(int arr[])
45+
{
46+
int n = arr.length;
47+
for (int i=0; i<n; ++i)
48+
System.out.print(arr[i]+" ");
49+
System.out.println();
50+
}
51+
52+
53+
public static void main(String args[])
54+
{
55+
int arr[] = {10, 7, 8, 9, 1, 5};
56+
int n = arr.length;
57+
58+
QuickSort ob = new QuickSort();
59+
ob.sort(arr, 0, n-1);
60+
61+
System.out.println("sorted array");
62+
printArray(arr);
63+
}
64+
}
65+

0 commit comments

Comments
 (0)