I would like to create an array which has 99 elements using function rand(). I created, and sorted with function bubblesort. But I met something that I cannot construe. The array was sorted as changed. The elements of array have changed. Why? What do you think about it? How it could be happen?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 99
void bubblesort(int[],int);
int main()
{
int response[SIZE];
int i;
srand(time(NULL));
for(i=0;i<SIZE;i++){
response[i]= 1 + rand()%9;
}
printf("An Array which is created with function rand() :\n");
for(i=0;i<SIZE;i++) {
if(i%10==0) {
printf("\n%3d",response[i]);
}
else
printf("%3d",response[i]);
}
bubblesort(response,SIZE);
printf("\n\n\nAfter using bubble sort, Array :\n");
for(i=0;i<SIZE;i++) {
if(i%10==0) {
printf("\n%3d",response[i]);
}
else
printf("%3d",response[i]);
}
return 0;
}
void bubblesort(int array[],int length)
{
int pass,compare,hold;
for(pass=0; pass<length; pass++){
for(compare=0; compare<length-1; compare++){
if(array[compare] > array[compare+1]){
//int hold;
hold = array[compare];
array[compare] = array[compare+1];
array[compare+1] = array[compare];
}
}
}
}
*I tried to this programme with small-scale numbers. And it worked successfully. The programme with small-scale numbers is in the following:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
void bubblesort(int[],int);
int main()
{
int response[SIZE];
int i;
srand(time(NULL));
for(i=0;i<SIZE;i++){
response[i]= 1+ rand() %3;
}
for(i=0;i<SIZE;i++){
printf("%3d",response[i]);
}
bubblesort(response,SIZE);
printf("\n\n\nAfter using bubble sort, Array :\n");
for(i=0;i<SIZE;i++) {
printf("%3d",response[i]);
}
return 0;
}
void bubblesort(int array[],int length)
{
int pass,hold,compare;
for(pass=0;pass<length;pass++) {
for(compare=0;compare<SIZE-1;compare++) {
if(array[compare]>array[compare+1]) {
hold = array[compare];
array[compare]=array[compare+1];
array[compare+1]=hold;
}
}
}
}