-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuicksort1.java
More file actions
147 lines (88 loc) · 1.92 KB
/
Quicksort1.java
File metadata and controls
147 lines (88 loc) · 1.92 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.util.Random;
import java.util.Scanner;
/**
*
* @author ELCOT
*/
public class Quicksort1
{
private int[] a;
void input ()
{
Scanner sc = new Scanner (System.in);
Random rm = new Random ();
System.out.print ("Enter the total numbers: ");
int n = sc.nextInt ();
a = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = rm.nextInt (1000); // Generates random numbers 0-999
}
}
void display ()
{
for (int i:a)
{
System.out.print (i + " ");
}
}
void sort ()
{
quicksort (0, a.length - 1);
}
void quicksort (int left, int right)
{
if (left < right)
{
int s = partition (left, right);
quicksort (left, s - 1);
quicksort (s + 1, right);
}
}
int partition (int left, int right)
{
int pivot = a[left];
int i = left;
int j = right + 1;
do
{
do
{
++i;
}
while (i < right && a[i] < pivot);
do
{
--j;
}
while (a[j] > pivot);
swap (i, j);
}
while (i < j);
swap (i, j); // undo last swap
swap (left, j);
return j;
}
private void swap (int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main (String args[])
{
Quicksort1 sorter = new Quicksort1 ();
sorter.input ();
System.out.println ("Array before sorting");
sorter.display ();
long startTime = System.nanoTime ();
sorter.sort ();
long endTime = System.nanoTime ();
double duration = (endTime - startTime) / 1000000.00;
//divide by 1000000 to get milliseconds.
System.out.println ("\nArray After sorting");
sorter.display ();
System.out.println ("\nTime for sorting is " + duration +
" milli seconds");
}
}