-1

So I'm a complete beginner and I wanted to try some sorting algorithm which I'm unable to do.

So this is just a blueprint of something that I wanted to begin with:

    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];
            }
        }
    }

and than somehow cut out the "merker" for every while loop, till I lay it out like that x[1] = 1 , x[2] = 2

The first while loop would stop when n = 0 which I would have made by cutting out every number that gets sorted in to the other algorithm.

Now it doesn't works at all, and I'm sure I've made tons of mistakes.

At the " merker == x[0]; " position it says, "variable x might not have been initialized.

I hope for help, I'm am extreme noob.

WJS
  • 36,363
  • 4
  • 24
  • 39
Laffa Yett
  • 17
  • 3

1 Answers1

0

There are multiple things going wrong in your code. Firstly, you haven't initialized array x[]. Secondly, you don't update the value of n so the while loop is sort of an infinite loop.

You can use bubble sort to order the elements as below:

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);
    }
}
vatsal gosar
  • 177
  • 7