Sorting algorithm four direct selection sort __ data structure and algorithm

Source: Internet
Author: User
1, directly select the concept of sorting:

Select the smallest element from the disordered area and put it directly into the end of the ordered area.

The direct selection sort and the direct insertion sort, all divide the data into ordered and unordered areas, the difference is that the direct insertion sort is to insert the first element of the unordered area directly into the ordered area to form a larger ordered region, and the direct selection order is the last of the smallest element from the disordered area to the ordered area. 2, direct selection of sorting characteristics:

Time complexity: O (n^2) (best time complexity: O (n^2) The worst time complexity O (n^2))

Complexity of Space: O (1)

Stability: Unstable

Note:

(1) After each trip of the select sort and bubble sort, there is an element in the final position. (leftmost or most right)

(2) Select the number of comparisons in the sorting process regardless of the initial state of the sequence, all the best and worst time complexity is O (n^2)

3. Implementation steps:

Set Array to arr[0...n-1]

1. Initialization array is unordered area arr[0...n-1]. Make I=0

2. Select a minimum element in the unordered area arr[0...n-1], swap it with Arr[i], and then arr[0...i] form an ordered area.

3.i++ and repeats the second step until the i==n-1, sorting is complete.

For example: The direct selection sort process for sequence {38,97,26,19,38*,15} is as follows:


4. Java Code Implementation

public void Selectsort (int[] arr) {
      int n = arr.length;
      for (int i = 0;i<n;i++) {
          int minindex = i;//Set the position of the smallest element for
          (int j = i+1;j<n;j++) {
              if (arr[j]<arr[ Minindex]) {
                   minindex = j;
              }
           }
           Place this element at the beginning of the unordered section
           int temp = arr[i];
           Arr[i] = Arr[minindex];
           Arr[minindex] = temp;
      }
}



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.