0

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!

LEARNER
  • 123
  • 1
  • 9
  • @LEARNER What is this code doing?! – Vlad from Moscow May 30 '20 at 22:10
  • You can look up "insertion sort" for some ideas. – lurker May 30 '20 at 22:36
  • I was just about to submit an answer when this question was closed! I believe the bug in your algorithm is this block: `{ k++; j++; }` -- it's possible for `j` to go out of bounds. It really should continue back to the top of the loop to increment `j` and check bounds: `{ k++; continue; }` – cdlane May 30 '20 at 23:49
  • I don't believe the "similar question" qualifies as it only inserts one item into a linked list wereas this program converts an array into a linked list. The other question is linked-list-centric, this one is array-centric and worthwhile. – cdlane May 30 '20 at 23:53

0 Answers0