About bubble sort and select sort

Source: Internet
Author: User

Bubble sort is the first contact of the sorting method, the idea is very simple, two-layer cycle, the number of neighbors compared to the small rise of large sinking.

As for the choice of sorting, the idea is somewhat similar to the insertion sort, but the range of comparisons becomes from the current number I to n-1, find the smallest number, write down the subscript, and complete an exchange in the outer loop. However, a decision on the size comparison needs to be made before swapping, thus saving the cost in some way.

Bubblesort:

1         Final int[] arr={57,68,59,52};2          for(inti=0;i<arr.length;i++){3             /*The reason why 1 is required here is that the inner comparison is the comparison between the current number and the latter number, and if the inner loop can go to the last number, the array will be out of bounds exception*/4              for(intj=i;j<arr.length-i-1;j++){5                 if(arr[j]>arr[j+1]){6                     inttemp;7Temp=arr[j+1];8arr[j+1]=Arr[j];9arr[j]=temp;Ten                 } One             } A}

Selectionsort:

1         int[] arr={57,68,59,52};2         3          for(inti=0;i<arr.length;i++){4             intminindex=i;5              for(intj=i+1;j<arr.length;j++){6                 if(arr[j]<Arr[minindex])7minindex=J;8             }9             /*before swapping, you need to add a comparison validation process*/Ten             if(arr[i]>Arr[minindex]) { One                 inttemp; Atemp=Arr[minindex]; -arr[minindex]=Arr[i]; -arr[i]=temp; the             } -  -}

About bubble sort and select sort

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.