C++实现选择排序
更新:HHH   时间:2023-1-7


#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;
}

返回编程语言教程...