-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickSortP2.java
76 lines (65 loc) · 1.64 KB
/
QuickSortP2.java
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
70
71
72
73
74
75
76
import java.util.*;
public class QuickSortP2
{
static int partition(int ar[], int minpos, int maxpos)
{
int p = ar[minpos];
ArrayList<Integer> leftlist = new ArrayList<Integer>();
ArrayList<Integer> rightlist = new ArrayList<Integer>();
for(int i = minpos+1 ; i <= maxpos; i++)
{
if(ar[i] > p)
{
rightlist.add(ar[i]);
}
else
{
leftlist.add(ar[i]);
}
}
copy(leftlist,ar,minpos);
int ppos = leftlist.size()+minpos;
ar[ppos] = p;
copy(rightlist,ar,ppos+1);
return minpos + leftlist.size();
}
static void copy(ArrayList<Integer> list, int ar[], int startIdx)
{
for(int num : list)
{
ar[startIdx++] = num;
}
}
static void quickSort(int ar[], int minpos, int maxpos)
{
if(minpos >= maxpos)
return;
int pos = partition (ar,minpos,maxpos);
quickSort(ar,minpos,pos-1);
quickSort(ar,pos+1,maxpos);
printArray(ar,minpos, maxpos);
}
static void printArray(int[] ar,int start, int end)
{
for(int i = start; i <= end;i++)
{
System.out.print(ar[i]+" ");
}
System.out.println("");
}
static void quickSort(int[] ar)
{
quickSort(ar,0,ar.length-1);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i=0;i<n;i++)
{
ar[i]=in.nextInt();
}
quickSort(ar);
}
}