简体   繁体   中英

Display each for loop iteration output in android studio

I am trying demonstrate insertion sort triggered by button click. Showing all steps of sorting in output.

Input Integer single digit 0-9.

Can someone help me improvising my code! Help would be much appreciated.

O/p displays braces and comas coz its an array. Can i get o/p without braces and comas!? instead of o/p [3,5,7,9] it should be like- 3 5 7 9

    public void btnClickMe(View v) {
    Button button = (Button) findViewById(R.id.button);
    EditText et = (EditText) findViewById(R.id.editText);
    TextView tv = (TextView) findViewById(R.id.textView2);
    insertionSort();
}
public void insertionSort(){
    EditText et = (EditText) findViewById(R.id.editText);
    String text = et.getText().toString();
    String txt1 = text.replaceAll(","," ");
    String txt= txt1.replaceAll(" ","");
    int[] array = new int[txt.length()];
    for (int i = 0; i < txt.length(); i++){
        array[i] = Character.getNumericValue(txt.charAt(i));
    }
    TextView tv = (TextView) findViewById(R.id.textView2);
    tv.setText("Output:");
    for (int j = 1; j < array.length; j++){
        int key = array[j];
        int i = j - 1;
        while ((i > -1) && (array[i] > key)){
            array[i + 1] = array[i];
            i--;
        }
    }
    array[i + 1] = key;
    tv.append(Arrays.toString(array).replaceAll(",","")+"\n");
}

I maybe asking too much but im trying to learn android and your help will teach me many new things. Thanks in advance.

First, your insertion algorithm is flawed. Second, you need to reset the TextView 's text before appending each time.

int[] array = {6, 4, 3, 2};
// TextView tv = (TextView) findViewById(R.id.textView2);
// Resets the text to be blank.
// tv.setText("");

for (int i = 1; i < array.length; ++i) {
    int j = i;
    while (j > 0 && array[j - 1] > array[j]) {
        int temp = array[j];
        array[j] = array[j - 1];
        array[j - 1] = temp;
        --j;
    }
    System.out.println(Arrays.toString(array));
    // i.e. [4, 6, 3, 2]
    // tv.append(Arrays.toString(array) + "\n");
}

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