冒泡
package com.sort;
/**
* 使用冒泡排序对数组进行排序
*
*/
public class TestSortMaopao {
public static void main(String[] args) {
int arr[] = new int[] {34,45,213,2,23};
for (int i = 0; i < arr.length - 1 ; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if(arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//遍历数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
}
}
直接选择
package com.sort;
public class TestSortZhiJieXuanZe_good {
public static void main(String[] args) {
int arr[] = new int[] {34,45,213,2,23,8};
for (int i = 0; i < arr.length - 1; i++) {
int t = i; //默认第一个最小
for (int j = i; j < arr.length; j++) {
if(arr[t] > arr[j]) {
t = j; //只记录位置
}
}
if( t != i) { //判断此时的i值是否为当时的最小值,若和最初的值不相等证明存在更小的值
int temp = arr[t]; //若此时不是最小的值,则交换
arr[t] = arr[i];
arr[i] = temp;
}
}
//遍历
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
}
}