#pragma once
void SelectSort(int* array, int n)
{
assert(array);
int left = 0;
int right = n-1;
while (left < right)
{
int minIndex = left;
int maxIndex = right;
for (int i = left; i <= right; ++i)
{
if (array[i] < array[minIndex])
minIndex = i;
if (array[i] > array[maxIndex])
maxIndex = i;
}
swap(array[left], array[minIndex]);
if (left == maxIndex)//调整maxIndex
maxIndex = minIndex;
swap(array[right], array[maxIndex]);
++left;
--right;
}
}
void SelectSortTest()
{
int array[] = {9, 4, 6, 5, 8, 3, 7, 1, 2, 0};
SelectSort(array, sizeof(array)/sizeof(array[0]));
for (size_t i = 0; i < sizeof(array)/sizeof(array[0]); ++i)
{
cout<<array[i]<<" ";
}
cout<<endl;
}#include <iostream>
using namespace std;
#include <assert.h>
#include "SelectSort.h"
int main()
{
SelectSortTest();
return 0;
}本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1787210
原文:http://zgw285763054.blog.51cto.com/11591804/1787210