I wanted to create a sorted linked list from an unsorted array, but my implementation doesn't work properly for example if I inserted :
6 5 4 3 2 1
The output is:
3 3 3 4 5 6
Here's the code:
list* insert(list* head,int* arr,int size)
{
int *index;
index=(int*)calloc(size,sizeof(int));
int i,j,k;
for(i=0;i<size;i++)
{
for(k=j=0;j<size;j++)
{
if(index[k]==-1) {k++;j++;}
if(arr[k]<=arr[j] && index[j]!=-1)
k=j;
}
index[k]=-1;
list* node=(list*)malloc(sizeof(list));
node->data=arr[k];
node->next=head;
head=node;
}
return head;
}
Can I get some help to improve my algorithm? if you have a better aproach please share it. thanks in advance!