冒泡排序
public static void bubbleSort() {
int[] arr = {12,78,34};
for(int i =0;i<arr.length-1;i++) {
for(int j=0;j<arr.length-i-1;j++) {//-1为了防止溢出
if(arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
选择排序
public static void selectSort(int[] a) {
if((a == null) || (a.length == 0))
return ;
for(int i = 0;i < a.length - 1;i ++){
int minIndex = i; // 无序区的最小数据数组下标
for(int j = i + 1;j < a.length;j ++){
// 在无序区中找到最小数据并保存其数组下标
if(a[j] < a[minIndex]){
minIndex = j;
}
}
// 将最小元素放到本次循环的前端
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
网友评论