C + + Select Sort Algorithm instance _c language

Source: Internet
Author: User

Select sort

Selection sorting is a simple and intuitive sort algorithm, and its working principle is as follows. The smallest (Large) element is first found in the unordered sequence, placed at the start of the sort sequence, and then continues to look for the smallest (large) element from the remaining unsorted elements and then to the end of the sorted sequence. And so on until all the elements are sorted.

The primary advantage of selecting a sort is related to data movement. If an element is in the correct final position, it is not moved. Select the sort to exchange a pair of elements each time, at least one of them will be moved to its final position, so the table of n elements is sorted in total for up to n-1 exchanges. In all sorts of sorting methods that rely entirely on swapping to move elements, choosing a sort is a very good one. The time complexity of selecting a sort is also O (n^2).

Code implementation

Copy Code code as follows:

#include <iostream>
using namespace Std;

void Selectsort (int arr[], int length)
{
int temp, min;
for (int i = 0; i < length-1; ++i)
{
min = i;

Looking for the minimum value
for (int j = i + 1; j < length; ++j)
{
if (Arr[j] < arr[min])
min = j;
}

Exchange
if (min!= i)
{
temp = Arr[i];
Arr[i] = Arr[min];
Arr[min] =temp;
}
}
}

int main ()
{
int arr[10] = {2, 4, 1, 0, 8, 4, 8, 9, 20, 7};

Selectsort (arr, sizeof (arr)/sizeof (arr[0));

for (int i = 0; i < sizeof (arr)/sizeof (arr[0)); ++i)
{
cout<<arr[i]<< "";
}
cout<<endl;

return 0;
}

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.