Search code examples
javabubble-sort

Bubble-sort with user's input = error


There is some mistake when I try to call my bubble sort class. But I cannot find it. This is my bubble sort class, which should be ok:

public static void Sort2(double[] yourNumbers) {
        double swap; 
        for(int i = 0; i < yourNumbers.length-1; i++){
            for(int d = 0; d < yourNumbers.length-1; d++){
                if(yourNumbers[d] > yourNumbers[d+1]){ 
                    //swap feature
                    swap = yourNumbers[d];
                    yourNumbers[d] = yourNumbers[d+1];
                    yourNumbers[d+1] = swap;

                }
            }
        }
    }

and this is my main method (and here when I call the Sort2 method I got an error:

The method Sort2(double[]) in the type sort.java is not applicable for the arguments (int)

        System.out.println("Size");
        int yourNumbers = scan.nextInt();
        double[] array = new double[yourNumbers];

        System.out.println("Numbers");

        for(int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
            array[i] = scan.nextDouble();

        }
            Sort2(array);

I know it was asked here so many times, but I feel I can't get it right. Please can you help me ? PS: I am not allowed to use an ArrayList.

EDIT : THis is code i used now. Stil wont work: Edit 2 : With help of this http://www.leepoint.net/notes-java/data/arrays/70sorting.html I got that. One line solves everything

import java.util.Scanner;

public class Bublesort{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Size");
        int yourNumbers = scan.nextInt();
        double[] array = new double[yourNumbers];

        System.out.println("Numbers");

        for(int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
            array[i] = scan.nextDouble();
         }

       Sort2(array);
    **System.out.println(Arrays.toString(array));** 

    }
    public static void Sort2(double[] yourNumbers) {
        double swap; 
         for(int i = 0; i < yourNumbers.length - 1; i++){
                for(int d = i + 1; d < yourNumbers.length; d++){
                    if(yourNumbers[i] > yourNumbers[d]){ 
                        //swap feature
                        swap = yourNumbers[i];
                        yourNumbers[i] = yourNumbers[d];
                        yourNumbers[d] = swap;

                    }
                }
            }

    }}

Solution

  • In order to use ArrayList you must import java.util.ArrayList; You are getting the error because you are passing an integer to your Sort2() function. You need to pass it an array of doubles. Also, your sort2 function will sort the array, but you will have no way to reference it, because java passes arguments by value.. you should have your function double[] sort2(double[] array) and then return the sorted array.