Thoughts (in ascending order):
1. Compare the size between two adjacent data to ensure that the larger value is at the back, and finally, after one sorting, the maximum value in the current group will be selected and placed in the last place;
2. In the array of excluding the last maximum value, select a maximum value and place it in the last digit;
3. Until the array length - 1 maximum value is excluded (selected), the sorting is completed;
For example: the array is {10, 34, 300, 56, 6, 56, 7, 87, 5} and the length of the array is 9;
public class find_em { public static void main(String[] args){ int arr[]={10,34,300,56,6,56,7,87,5}; System.out.println("原始数据:"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+"\t"); } System.out.println( "\nSort (ascending):" ); // Bubble sort for ( int j=1;j<arr.length;j++ ){ //Control the number of loops, that is, stop for ( int i=0;i<arr.length- j;i++ ){ //Exchange data, select the maximum value if (arr[i] > arr[i+1 ]){ //If it is descending order, just change it to < sign int t=arr[i+ 1 ]; arr[i+1]=arr[i]; arr[i]=t; } } for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+"\t"); } System.out.println( "Select this maximum value: "+arr[arr.length- j]); } System.out.println( "sorted data:" ); for ( int i=0;i<arr.length;i++ ){ System.out.print(arr[i]+"\t"); } } }
result:
Raw data: 10 34 300 56 6 56 7 87 5 Sort (ascending): 10 34 56 6 56 7 87 5 300 Select this maximum value: 300 10 34 6 56 7 56 5 87 300 Select the maximum value this time: 87 10 6 34 7 56 5 56 87 300 Select this maximum value: 56 6 10 7 34 5 56 56 87 300 Select this maximum value: 56 6 7 10 5 34 56 56 87 300 Select the maximum value this time: 34 6 7 5 10 34 56 56 87 300 Select the maximum value this time: 10 6 5 7 10 34 56 56 87 300 Select this maximum value: 7 5 6 7 10 34 56 56 87 300 Select this maximum value: 6 Sorted data: 5 6 7 10 34 56 56 87 300