冒泡排序
package sort;
public class BubbleSortDemo {
public static void main(String[] args) {
boolean flag = false;
int[] a = {2,5,114,31,1,160};
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-1-i; j++) {
if(a[j]>a[j+1]){
flag = true;
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
if(!flag){
break;
}else{
flag = false;
}
}
for (int i : a) {
System.out.println(i);
}
}
}
选择排序
package sort;
import java.util.Arrays;
public class SelectSortDemo {
public static void main(String[] args) {
int[] arr = new int[]{101, 34, 119, 1, 52, 38,67,96,23,15,2,111};
for (int i = 0; i < arr.length-1; i++) {
int minIndex = i;
int min = arr[i];
//主要是要记得让j=i+1,避免重复判断。
for (int j = i + 1; j < arr.length; j++) {
if(min > arr[j]){
min = arr[j];
minIndex = j;
}
}
//将最小值放在arr[0],即交换
if(minIndex != i){
arr[minIndex] = arr[i];
arr[i] = min;
}
System.out.println(Arrays.toString(arr));
}
}
}