Skip to content

Commit

Permalink
11_sorts: more tight boundary for selectionSort() and remove minValue
Browse files Browse the repository at this point in the history
It is for sure a[i] == a[j], when i == j. So we could skip those cases.

And minValue could be represented by a[minIndex], so replace minValue
with a[minIndex].

Signed-off-by: Wei Yang <[email protected]>
  • Loading branch information
RichardWeiYang committed Oct 15, 2018
1 parent b9ed4f1 commit be96922
Showing 1 changed file with 3 additions and 5 deletions.
8 changes: 3 additions & 5 deletions java/11_sorts/Sorts.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ public static void insertionSort(int[] a, int n) {
// 选择排序,a表示数组,n表示数组大小
public static void selectionSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 0; i < n; ++i) {
for (int i = 0; i < n - 1; ++i) {
// 查找最小值
int minIndex = i;
int minValue = a[i];
for (int j = i; j < n; ++j) {
if (a[j] < minValue) {
minValue = a[j];
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
Expand Down

0 comments on commit be96922

Please sign in to comment.