选择排序

定义

是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
选择排序的主要优点与数据移动有关。如果某个元素位于正确的最终位置上,则它不会被移动。选择排序每次交换一对元素,它们当中至少有一个将被移到其最终位置上,因此对 {\displaystyle n} n个元素的表进行排序总共进行至多 {\displaystyle n-1} {\displaystyle n-1}次交换。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。

代码

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <conio.h>

using namespace std;
const int SIZE = 10000;

void fSelectSort(int *pData, int size);

int main()
{
	int number;
	int fDate[SIZE] = { 0 };
	cout << "请输入需要进行排序的个数:";
	cin >> number;

	for (int i = 0; i < number; i++)
		cin >> fDate[i];
		
	fSelectSort(fDate, number);
	for (int i = 0; i < number; ++i)
		cout << fDate[i] << ' ';

	_getch();
	return 0;
}

void fSelectSort(int *pData, int size)
{
	for (int i = 0; i < size - 1; ++i)
	{
		int index = i;
		for (int j = i + 1; j < size; ++j)
		{
			if (pData[j] < pData[index])
				index = j;
		}
		if (index != i)
		{
			int temp = pData[i];
			pData[i] = pData[index];
			pData[index] = temp;
		}
	}
}

思路代码

#include <iostream>
#include <cstring>

using namespace std;
const int SIZE = 10000;

void fSelectSort(int *pData, int size);

int main()
{
	int number;
 	int fDate[SIZE] = { 0 };
	cout << "请输入需要进行排序的个数:";
	cin >> number;

	for (int i = 0; i < number; i++)
		cin >> fDate[i];
		
	fSelectSort(fDate, number);
	for (int i = 0; i < number; ++i)
		cout << fDate[i] << ' ';

	return 0;
}

void fSelectSort(int *pData, int size)
{
	for (int i = 0; i < size - 1; ++i)
	{
		int index = i;
		for (int j = i + 1; j < size; ++j)
		{
			if (pData[j] < pData[index])
				index = j;
		}
		if (index != i)
		{
			int temp = pData[i];
			pData[i] = pData[index];
			pData[index] = temp;

			printf("%-4d%-4d\n", pData[i], pData[index]);
			for (int i = 0; i < size; ++i)
				cout << pData[i] << ' ';
			cout << endl;
		}
	}
}

2018.12.9更新

定义代码:

void Selectsort(int a[], int n)
{
	int i, j, nMinIndex;
	for (i = 0; i < n; i++)
	{
		nMinIndex = i; //找最小元素的位置
		for (j = i + 1; j < n; j++)
			if (a[j] < a[nMinIndex])
				nMinIndex = j;
 
		Swap(a[i], a[nMinIndex]); //将这个元素放到无序区的开头
	}
}

作者:MoreWindows
来源:CSDN
原文:https://blog.csdn.net/MoreWindows/article/details/6671824

posted @ 2018-12-11 19:02  JingWenxing  阅读(164)  评论(0编辑  收藏  举报