Java implementation of common sorting algorithms-1

Source: Internet
Author: User

When we learn programming languages, we are exposed to many sort algorithms, and here we summarize the common sorting algorithms. Not regularly updated.

* Actually there are methods like Collections.sort () in Java that automatically sort us out, but the learning sort algorithm allows us to better understand a programming language.

1. Bubble Sort:

This algorithm is one of the most basic and famous algorithms.

1  Public Static voidBubblesort (int[] arr) {2      for(inti = 0; i < arr.length-1; i++) {3          for(j = 0; J < arr.length-1-I; j + +) {4             if(Arr[j] > arr[j + 1]) {5                 intt =Arr[j];6ARR[J] = arr[j + 1];7Arr[j + 1] =T;8             }9         }Ten     } One}

Note: The idea of the algorithm is that the previous element of the array is compared with the following element, if the previous element is larger, the value of the two elements is exchanged, so that the first round of the most important element is located in the last position of the array, that is, arr[arr.length-1]; The second round is that all elements except the last element are compared again to find the second largest number. And so on.

2. Select Sort:

The algorithm's popularity is quite similar to bubble sort.

1  Public Static voidSelectsort (int[] arr) {2      for(inti = 0; i < arr.length-1; i++) {3          for(intj = i + 1; J < Arr.length; J + +) {4             if(Arr[i] >Arr[j]) {5                 intt =Arr[i];6Arr[i] =Arr[j];7ARR[J] =T;8             }9         }Ten     } One}

Note: The idea of the algorithm is that the first element of the array is compared with all subsequent elements, if the element is larger, the value of two elements is exchanged, so that the first round of the most important element is located in the last position of the array, that is, arr[arr.length-1]; Then the second element is compared to all subsequent elements. And so on.

Java implementation of common sorting algorithms-1

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.