Skip to content Skip to sidebar Skip to footer

Bubble Sort App With User Input In Android Studio

I am new to android programming and I tried to do bubble sort by inputting numbers in one EditText and the sorted numbers will be outputted on the textview. The program has stopped

Solution 1:

you don't have initialized num. use following code

publicvoidBubbleSort() {
    Spannable spn = Input.getText();

    num = newint[spn.length()];
    int count = 0;
    for (int i = 0; i < spn.length(); i++){
        if((spn.charAt(i)+"").matches(".*\\d.*")){

            num[i] = Integer.parseInt(""+spn.charAt(i));
            count++;
        }
    }

    for (i = 0; i < count; i++) {
        for (j = i + 1; j < count; j++) {
            if (num[i] > num[j]) {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }

    String result = "";
    for (int i = 0; i < num.length; i++){
        result += num[i] + " ";
    }
    Result.setText(result);

}

Solution 2:

Spannable spn = Input.getText().toString;

And your bubble sot logic is also wrong, right one is like this

int temp = 0;  
              for (i = 0; i < num.length-1; i++) {
             for (j = 0; j < num.length-1; j++) {
                       if (num[j] > num[j+1]) {
                       temp = num[j];
                       num[j] = num[j+1];
                      num[j+1] = temp;
            }
       }
  }

Post a Comment for "Bubble Sort App With User Input In Android Studio"