首页 > 解决方案 > 排序算法,数组,最小数字到最大数字?

问题描述

所以我是一个完整的初学者,我想尝试一些我无法做到的排序算法。

所以这只是我想要开始的一些事情的蓝图:

    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 可能尚未初始化。

我希望得到帮助,我是极端的菜鸟。

标签: javaalgorithmsorting

解决方案


您的代码中有多个问题。首先,您还没有初始化数组 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);
    }
}

推荐阅读