【发布时间】:2015-04-01 20:39:14
【问题描述】:
我正在使用 gcc 编译器在 Ubuntu 14.04 上编程。
我正在使用 rand(); 函数为数组的元素赋值。
( rand() % 101; 实际上,所以我没有得到高于 100 的值)
然后我想使用“选择排序”算法对数组的元素进行排序,但是当我打印(f)它们时,前两个元素是 0,即使我的数组上没有 0(大多数时间)。
这是我的代码,请查看、编译、试用并指导我:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j, tam_arreglo;
time_t t;
int *a;
int aux;
/* Here I'm asking for you to give me the size of the array and store it in tam_arreglo */
printf("Introduzca el tamaño del arreglo: \n");
scanf("%d",&tam_arreglo);
/* Making my array the size I just asked you */
int array[tam_arreglo];
srand((unsigned) time(&t));
/* Dynamic random filling of the array */
printf("El arreglo sin ordenar es: \n");
a = malloc(tam_arreglo * sizeof(int));
for(i = 0 ; i < tam_arreglo ; i++) {
a[i] = rand()%101;
printf("%d\n", a[i]);
}
free(a);
/* My 'Selection sort' algorithm */
for(i = 0; i < tam_arreglo; i++) {
for(j = i+1; j < tam_arreglo; j++) {
if(a[i] > a[j]) {
aux = a[i];
a[i] = a[j];
a[j] = aux;
}
}
}
/* Here's when I get the error, the first two elements printed are 0's */
printf("El arreglo ordenado es: \n");
for(i = 0; i < tam_arreglo; i++) {
printf("%d\n", a[i]);
}
return(0);
}
我做错了什么?
【问题讨论】:
-
SO 不是用于代码审查的网站,而是用于提问的网站。
-
你没有看到我的问题吗?
标签: c linux algorithm ubuntu selection-sort