Java programming question: Now enter n numbers, separated by commas; then you can choose to sort in ascending or descending order; press the submit key to display what sort is in on another page, the result is, provide reset

I was so depressed. I went to a small company for an interview today. I originally wanted to write the question and leave, but I didn't expect.... I was asked to do such a simple question, but I was stunned. It’s been too long since I sorted it out. Although it’s simple, I still write one myself, a lesson.make a fortunestick out tongue

Not much to say, let's put the code, I hope it can also help those who need it, hahaha.

method one:

Bubble Sort

String str = "1,2,3,4,5,6,7";

String[] arr= str.split(",");

for(int i = 0;i<arr.length - 1 ;i++) {

    for(int j = 1;j<arr.length - j - 1;j++) {

         if(arr[j] < arr[j + 1]) {//Descending order If it becomes arr[j] > arr[j + 1], it becomes ascending order

            temp = arr[ j + 1];

           arr[ j + 1] = arr[j];

           arr[j] = temp;

         }

    }

}

for(String ar : arr) {

system.out.println(ar );

}

Method Two:

Collection sort, Reverse sort String str = "1,2,3,4,5,6,7";

List<String> list = str.asList();

Collection.sort(list);//Ascending

for(String s : list ) {

    systom.out.println(s);

}

Collection.reverse(list);//Descending

for(String s : list ) {

    systom.out.println(s);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326490134&siteId=291194637