Skip to content

Commit 154dc2a

Browse files
committed
added sorting algo QuickSort
1 parent af39434 commit 154dc2a

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

Sorting Algorithms/QuickSort.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Java program for implementation of QuickSort
2+
class QuickSort
3+
{
4+
/* This function takes last element as pivot,
5+
places the pivot element at its correct
6+
position in sorted array, and places all
7+
smaller (smaller than pivot) to left of
8+
pivot and all greater elements to right
9+
of pivot */
10+
int partition(int arr[], int low, int high)
11+
{
12+
int pivot = arr[high];
13+
int i = (low-1); // index of smaller element
14+
for (int j=low; j<high; j++)
15+
{
16+
// If current element is smaller than the pivot
17+
if (arr[j] < pivot)
18+
{
19+
i++;
20+
21+
// swap arr[i] and arr[j]
22+
int temp = arr[i];
23+
arr[i] = arr[j];
24+
arr[j] = temp;
25+
}
26+
}
27+
28+
// swap arr[i+1] and arr[high] (or pivot)
29+
int temp = arr[i+1];
30+
arr[i+1] = arr[high];
31+
arr[high] = temp;
32+
33+
return i+1;
34+
}
35+
36+
37+
/* The main function that implements QuickSort()
38+
arr[] --> Array to be sorted,
39+
low --> Starting index,
40+
high --> Ending index */
41+
void sort(int arr[], int low, int high)
42+
{
43+
if (low < high)
44+
{
45+
/* pi is partitioning index, arr[pi] is
46+
now at right place */
47+
int pi = partition(arr, low, high);
48+
49+
// Recursively sort elements before
50+
// partition and after partition
51+
sort(arr, low, pi-1);
52+
sort(arr, pi+1, high);
53+
}
54+
}
55+
56+
/* A utility function to print array of size n */
57+
static void printArray(int arr[])
58+
{
59+
int n = arr.length;
60+
for (int i=0; i<n; ++i)
61+
System.out.print(arr[i]+" ");
62+
System.out.println();
63+
}
64+
65+
// Driver program
66+
public static void main(String args[])
67+
{
68+
int arr[] = {10, 7, 8, 9, 1, 5};
69+
int n = arr.length;
70+
71+
QuickSort ob = new QuickSort();
72+
ob.sort(arr, 0, n-1);
73+
74+
System.out.println("sorted array");
75+
printArray(arr);
76+
}
77+
}

0 commit comments

Comments
 (0)