Skip to content

Commit b3dca9e

Browse files
Quick Sort in Java
1 parent 0e8463c commit b3dca9e

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

sorting/QuickSort.java

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
Copyright (C) Deepali Srivastava - All Rights Reserved
3+
This code is part of DSA course available on CourseGalaxy.com
4+
*/
5+
6+
import java.util.Scanner;
7+
8+
public class QuickSort
9+
{
10+
private QuickSort(){} //this class is not for instantiation
11+
12+
public static void sort(int[] a, int n)
13+
{
14+
sort(a,0,n-1);
15+
}
16+
17+
private static void sort(int a[],int low,int up)
18+
{
19+
if(low>=up) /*zero or one element in sublist*/
20+
return;
21+
int p = partition(a,low,up);
22+
sort(a,low,p-1); /*Sort left sublist*/
23+
sort(a,p+1,up); /*Sort right sublist*/
24+
}
25+
26+
private static int partition(int[] a, int low, int up)
27+
{
28+
int temp,i,j,pivot;
29+
30+
pivot=a[low];
31+
32+
i=low+1; /*moves from left to right*/
33+
j=up; /*moves from right to left*/
34+
35+
while(i<=j)
36+
{
37+
while( a[i]<pivot && i<up )
38+
i++;
39+
40+
while( a[j] > pivot )
41+
j--;
42+
43+
if(i<j) /*swap a[i] and a[j]*/
44+
{
45+
temp=a[i];
46+
a[i]=a[j];
47+
a[j]=temp;
48+
i++;
49+
j--;
50+
}
51+
else /*found proper place for pivot*/
52+
break;
53+
}
54+
55+
/* Proper place for pivot is j */
56+
a[low]=a[j];
57+
a[j]=pivot;
58+
59+
return j;
60+
}
61+
62+
63+
public static void main(String[] args)
64+
{
65+
int i,n;
66+
int[] a = new int[20];
67+
Scanner scan = new Scanner(System.in);
68+
69+
System.out.print("Enter the number of elements : ");
70+
n = scan.nextInt();
71+
72+
for(i=0; i<n; i++)
73+
{
74+
System.out.print("Enter element " + (i+1) + " : ");
75+
a[i] = scan.nextInt();
76+
}
77+
78+
sort(a,n);
79+
80+
System.out.println("Sorted array is : ");
81+
for(i=0; i<n; i++)
82+
System.out.print(a[i] + " ");
83+
System.out.println();
84+
scan.close();
85+
}
86+
87+
}

0 commit comments

Comments
 (0)