Skip to content

Commit 628956a

Browse files
committed
sorting using quickselect to find K closest
1 parent 7891412 commit 628956a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Two Pointers/kClosest.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
/*
3+
Quickselect - We select a pivot, and two pointers,(i and j)
4+
i starts from arr's start - 1 and j starts from arr's start.
5+
If arr[j] is smaller than element at pivot i.e. arr[end], we
6+
increment i and replace arr[i] and arr[j]. Once we have reached
7+
j till end - 1. We put arr[end] i.e. pivot in appropriate locatio.
8+
We do this recursively for the left half and the right half, to
9+
make it sorted.
10+
*/
11+
public int[][] kClosest(int[][] points, int K) {
12+
int i= 0;
13+
int j = points.length - 1;
14+
while(i < j) {
15+
int mid = partition(points, i, j); // we will get index where pivot will end up
16+
if (mid == K) {
17+
break;
18+
} else if (mid < K) {
19+
i = mid + 1;
20+
} else {
21+
j = mid - 1;
22+
}
23+
}
24+
int[][] res = new int[K][2];
25+
for (int k=0; k<K; k++) {
26+
res[k][0] = points[k][0];
27+
res[k][1] = points[k][1];
28+
}
29+
return res;
30+
}
31+
32+
private int partition(int[][] points, int start, int end) {
33+
int[] pivot = points[end];
34+
int swapIndex = start - 1;
35+
for (int j = start; j<end; j++) {
36+
if (value(points[j]) < value(pivot)) {
37+
swapIndex++;
38+
swap(points, swapIndex, j); // swapping swapindex(i) and j
39+
}
40+
}
41+
//once all swaps have been done, put pivot to index swapindex(i) + 1
42+
swap(points, ++swapIndex, end);
43+
return swapIndex; // returning the final correct position of pivot
44+
}
45+
46+
private int value(int[] a) {
47+
return a[0]*a[0] + a[1]*a[1];
48+
}
49+
50+
private void swap(int[][] points, int i, int j) {
51+
int[] temp = points[i];
52+
points[i] = points[j];
53+
points[j] = temp;
54+
}
55+
}

0 commit comments

Comments
 (0)