I am currently found out a interesting and simple sorting algorithm, so I implemented it in with dynamically allocated array. Here is my code.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void positiveIntSort(int *array,int size);
void printArray(int array[],int size);
int main() {
int bigNum = 99999;
int *array = (int *) malloc (bigNum*sizeof(int));
int i,index,size;
printf("Enter the size of array: ");
scanf("%d",&size);
printf("Enter each element for array: ");
for(i = 0; i < size; i++) {
scanf("%d",&index);
array[index] = 1;
}
positiveIntSort(array,size);
printArray(array,size);
}
int positiveIntSort(int *array,int size) {
int i,j = 0;
int sortedArray[size];
for(i = 0; i < 99999,j < size; i++) {
if(array[i] == 1)
sortedArray[j++] = i;
}
memcpy(array,sortedArray,size);
printArray(sortedArray,size);
}
void printArray(int array[],int size) {
int i;
for(i = 0; i < size; i++) {
printf("%d\t",array[i]);
}
printf("\n");
}
So, basically what I am doing is if user input a number : a, I go to corresponding index, which is a in this case, and assign 1 to this array[a].
So I traverse again and print all the index with value 1. This way gives me a sorted array.
However, I have some trouble with the dynamically allocated array. Here is a sample output I have:
Enter the size of array: 5
Enter each element for array:23 12 45 63 38
12 23 38 45 63
12 1845015 0 0 0
So sorting is definitely working. However when I return the sorted array to the dynamically allocated array, the result messed up. I could not find the reason? Is the way I use memcpy incorrect?
Besides, is the complexity of this algorithm O(n). Is there anyway to make this algorithm better?
1.memcpy(..., sizeof(int) * size)indexis within the bounds of the array, and if it is, any other element not specifically set to1has an indeterminate value, sincemallocdoes not initialise the memory allocated. You should also allocate the memory after you input the number of elementssize, sobigNumis irrelevant. Moreover what is the magic number for ini < 99999? Did you intendi < bigNum(although not in scope)?