1 public class SortTest {
2 public static void main(String[] args) {
3 int[] source = {7,2,3,4,1,-1,6};
4 //bubbleSort(source);
5 //selectSort(source);
6 insertSort(source);
7 for(int i = 0; i < source.length;i++){
8 System.out.print(source[i] + " ");
9 }
10 }
11 /*
12 * 冒泡排序,时间复杂度最差,平均(O(n^2)),最好是O(n),空间复杂度 1.
13 * 我的第一次写法
14 */
15 public static void bubbleSort1(int[] source) {
16 for(int i = 0; i < source.length - 1; i++){
17 for(int j = 0; j < source.length - i - 1; j++){
18 if(source[j + 1] < source[j]){
19 int temp = source[j];
20 source[j] = source[j+1];
21 source[j+1] = temp;
22 }
23 }
24 }
25 }
26 /*
27 * 冒泡排序
28 * 好的写法:容易理解
29 */
30 public static void bubbleSort(int[] source) {
31 boolean exchange;
32 for (int i = source.length -1; i > 0 ; i--) {
33 exchange = false;
34 for(int j = 0; j < i; j++){
35 if(source[j + 1] < source[j]){
36 int temp = source[j];
37 source[j] = source[j+1];
38 source[j+1] = temp;
39 exchange = true;
40 }
41 }
42 if (!exchange) {
43 return;
44 }
45 }
46 }
47 /*
48 * 选择排序:首先在未排序序列中找到最小元素,存放到排列序列的起始位置,最差,平均都是O(n^2),
49 * 然后,再从剩余未排序序列中找到最小元素,存放到排列序列的末尾
50 */
51 public static void selectSort(int[] source){
52 for (int i = 0; i < source.length - 1; i++) {
53 for(int j = i + 1; j < source.length; j++){
54 if (source[i] > source[j]) {
55 int temp = source[i];
56 source[i] = source[j];
57 source[j] = temp;
58 }
59 }
60 }
61 }
62 /*
63 * 插入排序:
64 * 插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,
65 * 算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法
66 */
67 public static void insertSort(int[] source){
68 for (int i = 1; i < source.length; i++) {
69 for(int j = i; (j > 0) && (source[j] < source[j-1]); j--){
70 int temp = source[j];
71 source[j] = source[j-1];
72 source[j - 1] = temp;
73 }
74 }
75 }
76 /*
77 * Shell排序
78 * 先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。所有距离为dl的倍数的记录放在同一个组中。
79 * 先在各组内进行直接插入排序;然后,取第二个增量d2<d1重复上述的分组和排序,直至所取的增量dt=1(dt<dt-l<;…<d2<d1),
80 * 即所有记录放在同一组中进行直接插入排序为止。该方法实质上是一种分组插入方法。非稳定排序方法
81 */
82 }