选择排序选最大最小

#include <iostream>
#include <string>
#include<stdio.h>
using namespace std;
typedef int DataType;
//颠倒字符串
void print(char ch[],int n)
{
	char t;
	int x=n/2;
	for(int i=0;i<x;i++)
	{
		t=ch[i];
		ch[i]=ch[n-1-i];
		ch[n-i-1]=t;
	}	
}
//编写一个选择排序用于排序数组A[n + 1],从A[1]到A[n]这个区间中选出一个最大的和第一个做交换,从A[1]到A[n]中选出一个最小的和最后一个做交换,直到该区间缩小至只剩一个元素。
void printArray(const char msg[], DataType data[], int size) {
	int i = 0;
	printf("%s[", msg);
	for ( i = 0; i < size; i++)
	{
		printf("%d ", data[i]);
	}
	printf("]\n");
}
//交换数组A索引位置为x和y的值
void swap(DataType A[], int x, int y) {
	DataType tmp = A[x];
	A[x] = A[y];
	A[y] = tmp;
}

//在数组A的start和end区间,找到最大值,并与start位置交换值
void swapMax(DataType A[], int start, int end) {
	int max = start, i = start;
	for (; i <= end; i++) {
		if (A[i] > A[max]) {
			max = i;
		}
	}
	swap(A, start, max);
}

//在数组A的start和end区间,找到最小值,并与end位置交换值
void swapMin(DataType A[], int start, int end) {
	int min = end, i = start;
	for (; i <= end; i++) {
		if (A[i] < A[min]) {
			min = i;
		}
	}
	swap(A, end, min);
}


//数组大小需要作为参数传递, 每趟操作有两次循环开销
//考试建议用此方法,逻辑简单不容易出错,不考虑效率
void selectSort(DataType A[], int length) {
	int front = 0, back = length - 1, i = 0;
	for (; i <= back; i++) {
		swapMax(A, front, back);
		swapMin(A, front, back);
		front++;
		back--;
	}
}  

void main()
{
	char str[20];
	cin>>str;
	cout<<str<<endl;
	print(str,strlen(str));
	cout<<str<<endl;


	DataType A[] = { 1, 5, 23, 98, 2, 34, 11, 47, 9, 25 };
	int length = sizeof(A) / sizeof(DataType);
	printArray("原始:", A, length);
	selectSort(A, length);
	printArray("排序:", A, length); 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值