java - 排序算法,数组,最小数字到最大数字?
问题描述
所以我是一个完整的初学者,我想尝试一些我无法做到的排序算法。
所以这只是我想要开始的一些事情的蓝图:
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
int[] a = {11,7,8,3,15,13,9,19,18,10,4};
int[] x;
int merker = a[0]; // the merker has the value 11 now
int i = 1;
int n = a.length;
while(n != 0){
while(i < n ) {
if (a[i] < merker)
merker = a[i];
i = i + 1;
}
merker == x[0];
}
}
}
而不是以某种方式为每个while循环剪掉“merker”,直到我把它排成那样 x[1] = 1 , x[2] = 2
第一个 while 循环将在 n = 0 时停止,我会通过删除每个排序到另一个算法中的数字来实现。
现在它根本不起作用,我敢肯定我犯了很多错误。
在“ merker == x[0]; ”位置它说,“变量 x 可能尚未初始化。
我希望得到帮助,我是极端的菜鸟。
解决方案
您的代码中有多个问题。首先,您还没有初始化数组 x[]。其次,您不更新 n 的值,因此 while 循环有点像无限循环。
您可以使用冒泡排序对元素进行排序,如下所示:
public class Sorting {
public static void main(String[] args) {
int[] a = {11,7,8,3,15,13,9,19,18,10,4};
Arrays.stream(a).forEach(System.out::println);
int n = a.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
// swap temp and arr[i]
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
System.out.println("After sorting");
Arrays.stream(a).forEach(System.out::println);
}
}
推荐阅读
- objective-c - 目标 c:比较整数时的预期标识符错误
- java - 应用程序不播放声音或访问蓝牙和耳机的麦克风仅在扬声器中播放声音并使用扬声器 android 的麦克风
- javascript - 正则表达式匹配问题库中的每个问题
- numpy - 连接 ResNet-50 预测 PyTorch
- android-keystore - Android 密钥库 - 无法生成密钥对
- flutter - 有没有办法触发在颤动中收到的 FCM 通知的功能?
- javascript - 2个文件上传按钮的问题
- typescript - 使用规则验证 v-form 中的 vuetify v-text-field
- javascript - ReactJS - 使用 Mutation Observer 检测第三方 DOM 插入
- flutter - Flutter simple_animation 迁移