首页 > 编程语言 > 详细

C++实现选择排序

时间:2016-06-08 12:35:08      阅读:324      评论:0      收藏:0      [点我收藏+]
#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

C++实现选择排序

原文:http://zgw285763054.blog.51cto.com/11591804/1787210

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!