/**
* 选择排序
*/
public static void selectSort(int[] a){
int temp=0;//保存最小的那个数
int flag = 0;
int n = a.length;
for (int i = 0; i < n; i++) {
temp = a[i];
flag = i;
for (int j = i+1; j < n; j++) {
if (a[j]<temp) {//找比temp小的那个数
temp = a[j];//值交换
flag = j;//小标赋值
}
}
if (flag!=i) {//不等时才需要交换,相等时没有必要交换
a[flag] =a[i];//最小数和要比较的数进行交换
a[i] = temp;//要比较的数赋值
}
}
}
/**
*插入排序
*/
public static void insertSort(int[] a){
if (a!=null) {
for (int i = 1; i < a.length; i++) {
int temp = a[i],j=i;
if (a[j-1]>temp) {//前面的大于后面的
while (j>=1&&a[j-1]>temp) {//前面的大于后面的,前面的值付给后面的,后面下标对应减一
a[j] = a[j-1];
j--;
}
}
a[j] = temp;//提出的数付给该在的位置
}
}
}
/**
* 冒泡排序
*/
public static void bubbleSort(int[] a){
int n = a.length;
int temp;
for (int i = 0; i < n-1; i++) {
for (int j = n-1; j >i; --j) {
if (a[j]<a[j-1]) {
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}
排序算法
最新推荐文章于 2023-02-12 20:42:34 发布