File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ package sort ;
2+
3+ /**
4+ * @author wangjunwei87
5+ * @since 2019-03-10
6+ */
7+ public class KthSmallest {
8+
9+ public static int kthSmallest (int [] arr , int k ) {
10+ if (arr == null || arr .length < k ) {
11+ return -1 ;
12+ }
13+
14+ int partition = partition (arr , 0 , arr .length - 1 );
15+ while (partition + 1 != k ) {
16+ if (partition + 1 < k ) {
17+ partition = partition (arr , partition + 1 , arr .length - 1 );
18+ } else {
19+ partition = partition (arr , 0 , partition - 1 );
20+ }
21+ }
22+
23+ return arr [partition ];
24+ }
25+
26+ private static int partition (int [] arr , int p , int r ) {
27+ int pivot = arr [r ];
28+
29+ int i = p ;
30+ for (int j = p ; j <= r - 1 ; j ++) {
31+ if (arr [j ] < pivot ) {
32+ swap (arr , i , j );
33+ i ++;
34+ }
35+ }
36+
37+ swap (arr , i , r );
38+
39+ return i ;
40+ }
41+
42+ private static void swap (int [] arr , int i , int j ) {
43+ if (i == j ) {
44+ return ;
45+ }
46+
47+ int tmp = arr [i ];
48+ arr [i ] = arr [j ];
49+ arr [j ] = tmp ;
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments