Implementation of selecting sorting in the Java array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.