public static int[] insertSort(int[] sourceArray) {
int s;
int temp;
for (int i = 1; i < sourceArray.length; i++) {
temp = sourceArray[i];
s = i;
while (s > 0 && temp < sourceArray[s - 1]) {
sourceArray[s] = sourceArray[s - 1];
s = s - 1;
}
sourceArray[s] = temp;
}
return sourceArray;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
交换排序
冒泡排序
基本思想:
从左到右执行n次:比较相邻元素大小,谁大把谁放在右边
实现:
private static int[] bubbleSort(int[] sourceArray) {
for (int i = 0; i < sourceArray.length; i++) {
for (int j = 0; j < sourceArray.length - 1; j++) {
sortMaxAndPutItRight(sourceArray, j, j+1);
}
}
return sourceArray;
}
private static void sortMaxAndPutItRight(int[] sourceArray, int left, int right) {
if (sourceArray[left] > sourceArray[right]) {
int temp = sourceArray[right];
sourceArray[right] = sourceArray[left];
sourceArray[left] = temp;
}
}