简体   繁体   中英

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 unexpectedly once I click the input button. Please "tell me what is wrong" Thank you.

public class MainActivity extends AppCompatActivity {

TextView Result;
EditText Input;
Button ASButton;

int i,j,temp,num[];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ASButton = (Button) findViewById(R.id.button);
    Input = (EditText) findViewById(R.id.editText);
    Result = (TextView) findViewById(R.id.textView2);

    ASButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BubbleSort();
        }
    });
}

public void BubbleSort() {

    Spannable spn = Input.getText();
    for (int i = 0; i < spn.length(); i++){
        num[i] = Integer.parseInt(""+spn.charAt(i));
    }

    for (i = 0; i < num.length; i++) {
        for (j = i + 1; j < num.length; 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);

  }
}

you don't have initialized num. use following code

public void BubbleSort() {
    Spannable spn = Input.getText();

    num = new int[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);

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM