D
D
Den4_x2019-07-30 14:00:28
Java
Den4_x, 2019-07-30 14:00:28

Why does the sorting algorithm work wrong if I call it via a method?

package WorkSpace;
import Edition.Array;
import java.util.*;



public class WorkSpace { 
    public static void main(String args[]){
        
        Scanner scan = new Scanner(System.in);
        System.out.print("кол-во эл-ов массива: ");
        int scan_Number = scan.nextInt(); 
        
        int[] box1 = new int[scan_Number];        
        
        Array.array_Add(box1);     
        
        Array.array_Sort(box1);
        
    }
}

and the next code is from another folder, but the problem is not in the modifiers, because he sees everything. it's just that when I do it through a method, then everything is bad, but if I write everything in main (), then everything is fine.
package Edition;


public class Array{
    //СОРТИРОВКА массива
    public static void array_Sort(int[] array){
        
        boolean bool = false;        
        while (!bool){
            for(int i=0;i<array.length-1;i++){
                bool = true;
                if(array[i]>array[i+1]){                    
                    bool=false;                    
                    int tmp = array[i];
                    array[i]=array[i+1];
                    array[i+1]=tmp;
                }
            }                
        } 
        //ВЫВОД массива
        for(int i: array){
            System.out.print(i+" ");
        }
        System.out.println();
    }
        
        //ЗАПИСЬ массива
    public static void array_Add(int[] array){        
        for(int i = 0; i<array.length;i++){
            array[i]=(int)(Math.random()*(9+1)+1);                      
        }
        
        for(int i: array){
            System.out.print(i+" ");
        }
        System.out.println();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2019-07-30
@fshp

Because you are trying to implement a linear sorting algorithm in O(n), which is basically impossible.
The bubble needs a second loop inside the first one.
And sometimes it works because randomly wished it so and generated a sequence for you with the right number of inversions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question