选择排序------直接选择排序

        基本思想:每次从待排序的记录中选出排序码最小的记录,顺序放在已排序的记录序列的最后,直到最后完成全部排序。

那么排完序的结果被处理为非降序

--------参考文献   熊岳山,祝恩.数据结构与算法[M].北京:清华大学出版社,2013:105.

        注意:本程序采用了文件操作,注意在和.cpp文件相同的位置添加资源文件sort.txt。

#include<stdlib.h> 
#include<stdio.h>
#include<assert.h>
#define MaxSize 100

typedef int ElemType;
typedef ElemType* pAr;		//指向该类型的指针

int ReadTextToArry(pAr par)
{
	assert(par != NULL);
	int i = 0;
	FILE *fp;
	errno_t err = fopen_s(&fp, "sort.txt", "r");
	if (err != 0)	//如果打开文件失败,终止程序
	{
		exit(1);
	}

	while (!feof(fp))//当不为文件结尾时
	{
		fscanf_s(fp, "%d", &par[i++]);	//逐个将文件中的数据放入数组中
	}
	return i;
	fclose(fp);
}

void DirectSelectSort(pAr par, int n)
{
	assert(par != NULL);
	int i, j, k;
	ElemType temp;
	for (i = 0; i < n - 1; ++i)
	{
		k = i;
		for (j = i+1; j < n; ++j)
			if (par[j] < par[k])
				k = j;

		if (i != k)
		{
			temp = par[k];
			par[k] = par[i];
			par[i] = temp;
		}
	}
}

void Print(ElemType *par, int n)
{
	assert(par != NULL);
	assert(n > 0);
	for (int i = 0; i < n; i++)
	{
		printf("%-5d", par[i]);
	}
}

int main()
{
	ElemType ar[MaxSize];
	int n= ReadTextToArry(ar);
	Print(ar, n);
	printf("\n");
	DirectSelectSort(ar, n);
	Print(ar, n);
	return 0;
}
本程序在VS2017下运行通过

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/80715944