冒泡排序:
package com.lx.d_sort;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int a[] = {9,10,5,3,1};
int temp = 0;
int lastExchangeIndex = 0; //记录最后一次交换的下标
int sortBorder = a.length-1; //无序数列的边界,每次比较比到这里为止
boolean flag = true; // 标识变量,是否进行过交换
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < sortBorder; j++) {
if (a[j]>a[j+1]) {
flag = false;
temp =a[j+1];
a[j+1] = a[j];
a[j] = temp;
lastExchangeIndex = j; //更新最后一次比较位置
}
}
sortBorder = lastExchangeIndex;
if (flag) {//未进行交换直接退出程序
break;
}
System.out.println("排序后为:"+Arrays.toString(a));
}
}
}
选择排序:
package com.lx.d_sort;
import java.util.Arrays;
public class SelectSort {
public static void main(String[] args) {
int a[] = {7,8,3,5,9,3};
int temp = 0;
for (int i = 0; i < a.length-1; i++) {
int min = a[i];//设置每次循环的起始点为最小/大值
int minIndex = i;
for (int j = i+1; j < a.length; j++) {
if (min > a[j]) {
min = a[j];
minIndex = j;
}
}
//将最小值放在a[0],即交换
if (minIndex != i) {
a[minIndex] = a[i];
a[i] = min;
}
}
System.out.println("排序之后:"+Arrays.toString(a));
}
}