简单选择排序

yuananf 分享于 4天前 1029阅 0人收藏此代码, 我要收藏

简单选择排序,喜闻乐见

#include <iostream>

using namespace std;

void printArray(int* numbers, int length);
void simpleChooseSort(int* numbers, int length);
void swap(int *a, int *b);

int main()
{
	int numbers[] = {4,5,8,6,2,6,7,3,1,8,9,3};
	int length = sizeof(numbers)/sizeof(*numbers);

	cout << "before sort: ";
	printArray(numbers, length);

	simpleChooseSort(numbers, length);
	
	cout << "after sort: ";
	printArray(numbers, length);

	cin.get();
}

void printArray(int* numbers, int length)
{
	for(int i = 0; i < length; i++)
	{
		cout << numbers[i] << " ";
	}
	cout << endl;
}

void simpleChooseSort(int* numbers, int length)
{
	for(int i = 0; i < length; ++i)
	{
		int minIndex = i;
		for(int j = i; j < length; ++j)
		{
			minIndex = numbers[minIndex] > numbers[j] ? j : minIndex;
		}
		swap(&numbers[i], &numbers[minIndex]);
	}
}

void swap(int *a, int *b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}
//该代码片段来自于: http://www.sharejs.com/codes/cpp/8695