I wrote a program to run the insertion sorting algorithms. Everything seems good. But when I execute it there is a strange result. It seems that the programs uses garbage in memory. How could I fix it?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void insertion_inc(int Array[], int size)
{
int i, j, key;
for (i = 1; i < size; i++)
{
j = i - 1;
key = Array[i];
while (j >=0 && Array[j]>key )
{
Array[j + 1] = Array[j];
j--;
}
Array[j++] = key;
}
}
void insertion_dec(int Array[], int size)
{
int i, j, key;
for (i = 1; i < size; i++)
{
j = i - 1;
key = Array[i];
while (j >= 0 && Array[j] < key)
{
Array[j + 1] = Array[j];
j--;
}
Array[j++] = key;
}
}
void print_array(int arr[], int size)
{
for (int i = 0; i < size; i++)
printf(" %d ", arr[i]);
}
/////////////////////////////////////////////
int main()
{
time_t t;
srand((unsigned)time(&t));
int Arr[10];
int size = sizeof(Arr);
printf("The unsorted Array : \n ");
for (int i = 0; i < size;i++)
Arr[i] = rand()/10;
print_array(Arr, size);
printf("\n\n\n The sorted Array : \n");
insertion_inc(Arr, size);
print_array(Arr, size);
return 0;
}
**The output always looks like this : **
The unsorted Array :
12 23 54 87 2 68 29 57 97 12 -858993460 272204808 7601072 7742451 1 15039136 15044096 1 15039136 15044096 7601164 7742023 272204692 7738189 7738189 8462336 0 0 0 0 0 0 0 0 7775604 7775616 0 7601080 0 7601272
The sorted Array :
23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 57 68 7601272 7738189 7738189 7738189 7742023 7775616 8462336 8462336 8462336 15039136 15039136 15039136 15039136 15044096 272204692 272204808 272204808 272204808 272204808 272204808 272204808 272204808 272204808
Even when I ignore the use of srand()
and rand()
, there is still the problem.