冒泡排序
限制生成的随机数为0-100的五个数字,然后通过两重循环进行排序,最后遍历一维数组按照顺序输出
public class BubbelSort {
public static void main(String[] args) {
final int N = 5;
int[] numbers = new int[N];
Random random = new Random();
for(int i = 0; i < N; i++){
numbers[i] = random.nextInt(100);
}
System.out.print("排序前:");
//遍历一维数组
for (int n:numbers
) {
System.out.print(n+ " ");
}
//外层循环控制排序趟数
int temp;
for(int i = 0; i < N-1; i++){
//内层循环控制每趟的排序次数
for (int j = i+1; j < N; j++){
if (numbers[i] < numbers[j]){
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
System.out.print("\n排序后:");
for (int n:numbers
) {
System.out.print(n+ " ");
}
}
}
选择排序
public class selectSort {
public static void main(String[] args) {
final int N = 5;
int[] number = new int[N];
Random random = new Random();
for (int i = 0; i < N; i++){
number[i] = random.nextInt(100);
}
System.out.print("排序前:");
//遍历一维数组
for (int n:number
) {
System.out.print(n+ " ");
}
int min;
int temp;
for (int i = 0; i < N-1; i++){
min = i;
for (int j = i + 1; j< N; j++){
if (number[j] < number[min]){
min = j;
}
}
if (i != min){
temp = number[i];
number[i] = number[min];
number[min] = temp;
}
}
System.out.print("\n排序后的结果为:");
for (int n:number
) {
System.out.print(n+" ");
}
}
}
(转载)
作者:我就是个帝帝
链接:https://www.jianshu.com/p/84d8aa10b057
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。