The choice of 3.1.1 Brute force method

Source: Internet
Author: User

At the beginning of the selection sort, we scan the entire list, find its smallest element, and then swap with the first element, placing the smallest element in its final position in the ordered table. We then start by scanning the list from the second element, finding the smallest element in the last n-1 element, swapping the position with the second element, and placing the second smallest element in its final position. In general, when I scan the list for the first time (the value of I from 0 to n-2), the algorithm in the last N-i elements to find the smallest element, and then take it and the AI Exchange. After the n-1, the list is sorted out.

Algorithm pseudo-code (assuming the list is implemented by an array)

Selectionsort (a[0... n-1])// Input: A sortable array a[0...n-1]//  Output: Array in ascending order A[0...n-1] for i←0 to n2do    min←i      for j←i+1 to n1do        if a[j]<a[min]    min←j    Swap a[i] and a[min]

Number of executions

For any input, the selection sort is an θ (N2) algorithm. Note, however, that the key is swapped only for θ (n), or more precisely, n-1 times (I loop performs the interchange once for each repetition). This feature makes selection sorting preferable to other sorting algorithms.

C + + code

#include <iostream>using namespacestd;voidSelectionsort (intA[],intN) { for(inti =0; I < n1; i++) {        intMin =i;  for(intj = i +1; J < N; J + +) {            if(A[j] <a[min]) min=J;    } swap (A[i], a[min]); }}intMain () {intA[] = { the, $, the, -, in, the, -}; Selectionsort (A,sizeof(a)/sizeof(a[0]));  for(inti =0; I <sizeof(a)/sizeof(a[0]); i++) {cout<< A[i] <<" "; } cout<<Endl; return 0;}

The choice of 3.1.1 Brute force method

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.