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.
- Loading branch information
wangzheng
committed
Oct 14, 2018
1 parent
34b568f
commit 46266da
Showing
1 changed file
with
70 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,70 @@ | ||
package sorts; | ||
|
||
/** | ||
* 冒泡排序、插入排序、选择排序 | ||
* | ||
* Author: Zheng | ||
*/ | ||
public class Sorts { | ||
|
||
// 冒泡排序,a是数组,n表示数组大小 | ||
public static void bubbleSort(int[] a, int n) { | ||
if (n <= 1) return; | ||
|
||
// 提前退出标志位 | ||
boolean flag = false; | ||
for (int i = 0; i < n; ++i) { | ||
for (int j = 0; j < n - i - 1; ++j) { | ||
if (a[j] > a[j+1]) { // 交换 | ||
int tmp = a[j]; | ||
a[j] = a[j+1]; | ||
a[j+1] = tmp; | ||
// 此次冒泡有数据交换 | ||
flag = true; | ||
} | ||
} | ||
if (!flag) break; // 没有数据交换,提前退出 | ||
} | ||
} | ||
|
||
// 插入排序,a表示数组,n表示数组大小 | ||
public static void insertionSort(int[] a, int n) { | ||
if (n <= 1) return; | ||
|
||
for (int i = 1; i < n; ++i) { | ||
int value = a[i]; | ||
int j = i - 1; | ||
// 查找要插入的位置并移动数据 | ||
for (; j >= 0; --j) { | ||
if (a[j] > value) { | ||
a[j+1] = a[j]; | ||
} else { | ||
break; | ||
} | ||
} | ||
a[j+1] = value; | ||
} | ||
} | ||
|
||
// 选择排序,a表示数组,n表示数组大小 | ||
public static void selectionSort(int[] a, int n) { | ||
if (n <= 1) return; | ||
for (int i = 0; i < n; ++i) { | ||
// 查找最小值 | ||
int minIndex = i; | ||
int minValue = a[i]; | ||
for (int j = i; j < n; ++j) { | ||
if (a[j] < minValue) { | ||
minValue = a[j]; | ||
minIndex = j; | ||
} | ||
} | ||
|
||
// 交换 | ||
int tmp = a[i]; | ||
a[i] = a[minIndex]; | ||
a[minIndex] = tmp; | ||
} | ||
} | ||
|
||
} |