1. First to achieve the first goal
//define an array to top up the largest values Public classDemo02 { Public Static voidMain (String args[]) {int[] arr = {2,5,1,9,8}; Defines an array of arr for(inti=1;i<arr.length;i++{//start with the second number (array subscript 1) and compare to the first numberif(arr[i]>arr[0]){ inttemp =Arr[i]; Arr[i]= Arr[0]; arr[0] =temp; } } for(inti = 0;i<arr.length;i++) {//Output result System.out.print (Arr[i]+","); } }}
2. Achieving the second goal: placing the second largest number in second place
Add a code snippet after a for loop:
for (int i=2;i<arr.length;i++) { // starting with the third number (array subscript 2) and comparing with the second number, the first number is no longer in control. if (arr[i]>arr[1]) { int temp = arr[i]; = Arr[1]; arr[1] =temp; } }
3. And so on, achieve the third goal: Place the third largest number in the third-digit code snippet as follows:
for (int i=2;i<arr.length;i++) { if(arr[i]>arr[1]) { int temp = Arr[i]; = Arr[1]; arr[1] =temp; } }
4. When implemented to the second-to-last number, it is found that the implementation of the order from large to small, we are not difficult to find that the above code snippet has a very high repetition rate, it can be summarized as follows:
Public Static voidMain (String args[]) {int[] arr = {2,5,1,9,8}; for(intj = 0;j<arr.length-1;j++{//This outer loop controls the number of comparisons, as long as you compare the array length-1 times for(inti = j+1;i<arr.length;i++) {if(arr[i]>Arr[j]) { inttemp =Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; }}} System.out.println ("After sorting:");//after sorting is displayed for(inti = 0;i<arr.length;i++) {System.out.print (Arr[i]+","); } }}
Implementation of selecting sorting in the Java array