forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#266 from wangjunwei87/patch-1
找到一组数据的第K大元素
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package sort; | ||
|
||
/** | ||
* @author wangjunwei87 | ||
* @since 2019-03-10 | ||
*/ | ||
public class KthSmallest { | ||
|
||
public static int kthSmallest(int[] arr, int k) { | ||
if (arr == null || arr.length < k) { | ||
return -1; | ||
} | ||
|
||
int partition = partition(arr, 0, arr.length - 1); | ||
while (partition + 1 != k) { | ||
if (partition + 1 < k) { | ||
partition = partition(arr, partition + 1, arr.length - 1); | ||
} else { | ||
partition = partition(arr, 0, partition - 1); | ||
} | ||
} | ||
|
||
return arr[partition]; | ||
} | ||
|
||
private static int partition(int[] arr, int p, int r) { | ||
int pivot = arr[r]; | ||
|
||
int i = p; | ||
for (int j = p; j <= r - 1; j++) { | ||
if (arr[j] < pivot) { | ||
swap(arr, i, j); | ||
i++; | ||
} | ||
} | ||
|
||
swap(arr, i, r); | ||
|
||
return i; | ||
} | ||
|
||
private static void swap(int[] arr, int i, int j) { | ||
if (i == j) { | ||
return; | ||
} | ||
|
||
int tmp = arr[i]; | ||
arr[i] = arr[j]; | ||
arr[j] = tmp; | ||
} | ||
} |