[问题] 选择排序法

楼主: hth9494 (hth9494)   2016-01-21 23:45:34
开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)

问题(Question):
关于我写的选择排序法中,有一段地方,是要把当前的数字
与其他的数比较后交换位置,交换的部分有一点点问题。
程式码(Code):(请善用置底文网页, 记得排版)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() //选择排序法
{
time_t ts;
srand((unsigned int)time(&ts));
int a[10];
int i;
for (i = 0; i < 10; i++) //随机赋值
{
a[i] = rand() % 100; //值设在0~99间
printf("%d ", a[i]);
}
printf("\n");
//排序开始
int max;
for (i = 0; i < 9; i++)
{
max = i; //假设目前这个数是最大的数
int j;
for (j = i + 1; j < 10; j++)
{
if (a[max] < a[j])
{
max = j;
}
}
int temp = a[i]; //交换
a[i] = a[max];
a[max] = temp;
//a[max] = a[max] + a[i];
//a[i] = a[max] - a[i];
//a[max] = a[max] - a[i];
}
//排序结束
for (i = 0; i < 10; i++) //排序后打印
{
printf("%d ", a[i]);
}
getchar();
return 0;
}
补充说明(Supplement):
目前这个程式码跑起来结果没问题,但是请各位看一下交换的地方
用temp做交换没有问题,我跑起来是对的
可当我把temp做交换的那三行
换成下面被我注解掉的那三行程式码就错了
下面的那三行也能达到交换的效果才对啊
请问错在哪里呢,我找很久都找不到
请各位大大帮忙解惑,谢谢
楼主: hth9494 (hth9494)   2016-01-22 01:22:00
发现问题了~~不好意思

Links booklink

Contact Us: admin [ a t ] ucptt.com