Select sort C + + implementation

Source: Internet
Author: User

Select sort
Compare the size of the previous element with the last element in the array, and if the subsequent element is smaller than the previous element, use a variable K to remember his position,
Then the second comparison, the front "last element" now becomes "the previous element",
Continue to compare with his "latter element" if the latter element is smaller than he is, use the variable K to remember its position in the array (subscript),
By the end of the loop, we should find the lowest subscript of the number and then judge if the subscript of the element is not the subscript of the first element,
Let the first element swap with him for a value so that the smallest number in the entire array is found. Then find the second small number in the array, and let him exchange values with the second element in the array,
And so on
#include <iostream>
#include <array>
using namespace Std;


Template<class t>
void Selection_sort (t&, int);


int main ()
{
Array<int, 10> arr = {3,2,1,5,4,7,6,9,8,0};
Selection_sort (arr, arr.size ());


for (int i = 0; i <; i++)
{
cout << Arr[i] << Endl;
}




Cin.get ();
return 0;
}


Template<class t>
void Selection_sort (t& arr, int count)
{
int index = 0;
Auto min = arr[0];
for (int i = 0; i < count; i++)
{
min = Arr[i];
index = i;
for (int j = i+1; J < Count; J + +)//Find minimum value
{
if (Arr[j] < min)
{
min = Arr[j];
index = j;
}
}
if (Index! = i)//determines whether the subscript of the current minimum is not I, is not exchanged, is not a value exchange with the current I position
{
int temp = Arr[i];
Arr[i] = Arr[index];
Arr[index] = temp;
}
}
}

Select sort C + + implementation

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.