冒泡排序:
public static void main(String[] args) {
//冒泡排序
int[] arr = new int[]{4,2,5,7,1};
for(int x : arr) {
System.out.print(x + " ");
}
System.out.println("");
//冒泡排序
for(int i=0;i<arr.length-1;i++) {//排序次数,和内层循环没有关系
for(int j=0;j<arr.length-i-1;j++) {
if(arr[j]>arr[j+1]) {
int tmp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = tmp;
}
}
}
for(int x : arr) {
System.out.print(x + " ");
}
}
插入排序:
public static void main(String args[]) {
int[] array = new int[] {4,2,1,8,3,7,6,9,0};
for(int x : array) {
System.out.print(x + " ");
}
System.out.println();
int arrayLength = array.length;
int[] resultArray = new int[arrayLength];
resultArray[0] = array[0];//有序数列
int realLength = 1;
for(int i = 1;i<arrayLength ;i++) {
int tmp = array[i];
int insertPosition = -1;
int j = 0;
for(j = 0;j<realLength;j++) {
if(resultArray[j]>tmp) {
//插入到j位置的前面
insertPosition = j;
//j位置及以后的所有元素向后移动一位
for(int k = realLength-1;k>=insertPosition;k--) {
resultArray[k+1] = resultArray[k];
}
resultArray[insertPosition] = tmp;
break;
}
}
if(j>=realLength) {
resultArray[realLength] = tmp;
}
realLength ++;
}
for(int x : resultArray) {
System.out.print(x + " ");
}
}