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