Insertion Sort is giving bizarre output [on hold]











up vote
-6
down vote

favorite












I wrote a insertion sort program but it's not sorting the inputs correctly. Please help me find the error in the program.
If my input is 1 2 3 10 -1 -2 -3 then the output is



Value of a[0] is 1
Value of a[1] is 2
Value of a[2] is 3
Value of a[9] is -1
Value of a[10] is -2
Value of a[11] is -3
Value of a[19] is 10


I don't know if my logic is correct but I don't know where I did wrong please help me find the error in the program.



 #include<stdio.h>
void looper(int *);
void sort(int *,int *);
int main()
{
int a[25];
for(int i=0;i<=24;i++)
{
printf("Enter the value of a[%d] : ",i);
scanf("%d",&a[i]);
}
looper(a);
for(int i=0;i<=24;i++)
{
printf("Value of a[%d] is %dn",i,a[i]);
}
}
void looper(int *p)
{
for(int i=1;i<=24;i++)
{
for(int j=(i-1);j>=0;j--)
{
sort((p+i),(p+j));
}
}
}
void sort(int *a,int *b)
{
int tmp;
if((*a)<(*b))
{
tmp=*a;
*a=*b;
*b=tmp;
}
}









share|improve this question









New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











put on hold as off-topic by dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity Nov 10 at 16:35


This question appears to be off-topic. The users who voted to close gave this specific reason:


  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity

If this question can be reworded to fit the rules in the help center, please edit the question.









  • 2




    Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
    – WhozCraig
    Nov 10 at 14:00








  • 1




    It is a bubble sort. And the loop conditions in looper are suspicious.
    – Nelfeal
    Nov 10 at 14:01










  • @Nelfeal can you please help me out with the code? What changes would you do?
    – Debojeet Das
    Nov 10 at 14:04








  • 1




    Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
    – Nelfeal
    Nov 10 at 14:13












  • @Nelfeal Sure I understood that reference but for insertion sort what should I do?
    – Debojeet Das
    Nov 10 at 14:25















up vote
-6
down vote

favorite












I wrote a insertion sort program but it's not sorting the inputs correctly. Please help me find the error in the program.
If my input is 1 2 3 10 -1 -2 -3 then the output is



Value of a[0] is 1
Value of a[1] is 2
Value of a[2] is 3
Value of a[9] is -1
Value of a[10] is -2
Value of a[11] is -3
Value of a[19] is 10


I don't know if my logic is correct but I don't know where I did wrong please help me find the error in the program.



 #include<stdio.h>
void looper(int *);
void sort(int *,int *);
int main()
{
int a[25];
for(int i=0;i<=24;i++)
{
printf("Enter the value of a[%d] : ",i);
scanf("%d",&a[i]);
}
looper(a);
for(int i=0;i<=24;i++)
{
printf("Value of a[%d] is %dn",i,a[i]);
}
}
void looper(int *p)
{
for(int i=1;i<=24;i++)
{
for(int j=(i-1);j>=0;j--)
{
sort((p+i),(p+j));
}
}
}
void sort(int *a,int *b)
{
int tmp;
if((*a)<(*b))
{
tmp=*a;
*a=*b;
*b=tmp;
}
}









share|improve this question









New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











put on hold as off-topic by dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity Nov 10 at 16:35


This question appears to be off-topic. The users who voted to close gave this specific reason:


  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity

If this question can be reworded to fit the rules in the help center, please edit the question.









  • 2




    Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
    – WhozCraig
    Nov 10 at 14:00








  • 1




    It is a bubble sort. And the loop conditions in looper are suspicious.
    – Nelfeal
    Nov 10 at 14:01










  • @Nelfeal can you please help me out with the code? What changes would you do?
    – Debojeet Das
    Nov 10 at 14:04








  • 1




    Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
    – Nelfeal
    Nov 10 at 14:13












  • @Nelfeal Sure I understood that reference but for insertion sort what should I do?
    – Debojeet Das
    Nov 10 at 14:25













up vote
-6
down vote

favorite









up vote
-6
down vote

favorite











I wrote a insertion sort program but it's not sorting the inputs correctly. Please help me find the error in the program.
If my input is 1 2 3 10 -1 -2 -3 then the output is



Value of a[0] is 1
Value of a[1] is 2
Value of a[2] is 3
Value of a[9] is -1
Value of a[10] is -2
Value of a[11] is -3
Value of a[19] is 10


I don't know if my logic is correct but I don't know where I did wrong please help me find the error in the program.



 #include<stdio.h>
void looper(int *);
void sort(int *,int *);
int main()
{
int a[25];
for(int i=0;i<=24;i++)
{
printf("Enter the value of a[%d] : ",i);
scanf("%d",&a[i]);
}
looper(a);
for(int i=0;i<=24;i++)
{
printf("Value of a[%d] is %dn",i,a[i]);
}
}
void looper(int *p)
{
for(int i=1;i<=24;i++)
{
for(int j=(i-1);j>=0;j--)
{
sort((p+i),(p+j));
}
}
}
void sort(int *a,int *b)
{
int tmp;
if((*a)<(*b))
{
tmp=*a;
*a=*b;
*b=tmp;
}
}









share|improve this question









New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I wrote a insertion sort program but it's not sorting the inputs correctly. Please help me find the error in the program.
If my input is 1 2 3 10 -1 -2 -3 then the output is



Value of a[0] is 1
Value of a[1] is 2
Value of a[2] is 3
Value of a[9] is -1
Value of a[10] is -2
Value of a[11] is -3
Value of a[19] is 10


I don't know if my logic is correct but I don't know where I did wrong please help me find the error in the program.



 #include<stdio.h>
void looper(int *);
void sort(int *,int *);
int main()
{
int a[25];
for(int i=0;i<=24;i++)
{
printf("Enter the value of a[%d] : ",i);
scanf("%d",&a[i]);
}
looper(a);
for(int i=0;i<=24;i++)
{
printf("Value of a[%d] is %dn",i,a[i]);
}
}
void looper(int *p)
{
for(int i=1;i<=24;i++)
{
for(int j=(i-1);j>=0;j--)
{
sort((p+i),(p+j));
}
}
}
void sort(int *a,int *b)
{
int tmp;
if((*a)<(*b))
{
tmp=*a;
*a=*b;
*b=tmp;
}
}






c arrays sorting insertion-sort






share|improve this question









New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 10 at 15:34





















New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 10 at 13:57









Debojeet Das

13




13




New contributor




Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Debojeet Das is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




put on hold as off-topic by dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity Nov 10 at 16:35


This question appears to be off-topic. The users who voted to close gave this specific reason:


  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity

If this question can be reworded to fit the rules in the help center, please edit the question.




put on hold as off-topic by dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity Nov 10 at 16:35


This question appears to be off-topic. The users who voted to close gave this specific reason:


  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – dandan78, gsamaras, EJoshuaS, Pearly Spencer, Machavity

If this question can be reworded to fit the rules in the help center, please edit the question.








  • 2




    Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
    – WhozCraig
    Nov 10 at 14:00








  • 1




    It is a bubble sort. And the loop conditions in looper are suspicious.
    – Nelfeal
    Nov 10 at 14:01










  • @Nelfeal can you please help me out with the code? What changes would you do?
    – Debojeet Das
    Nov 10 at 14:04








  • 1




    Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
    – Nelfeal
    Nov 10 at 14:13












  • @Nelfeal Sure I understood that reference but for insertion sort what should I do?
    – Debojeet Das
    Nov 10 at 14:25














  • 2




    Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
    – WhozCraig
    Nov 10 at 14:00








  • 1




    It is a bubble sort. And the loop conditions in looper are suspicious.
    – Nelfeal
    Nov 10 at 14:01










  • @Nelfeal can you please help me out with the code? What changes would you do?
    – Debojeet Das
    Nov 10 at 14:04








  • 1




    Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
    – Nelfeal
    Nov 10 at 14:13












  • @Nelfeal Sure I understood that reference but for insertion sort what should I do?
    – Debojeet Das
    Nov 10 at 14:25








2




2




Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
– WhozCraig
Nov 10 at 14:00






Um.. maybe its because I've been awake for too long, but that looks an aweful lot like a non-optimized bubble sort; not insertion sort. Just saying. And your post should include your 25 numbers of input data. The expected result is somewhat obvious from that, so no need to specify that, but "it's not sorting the inputs correctly." tells a small part of the story; obviously it's not sorting them correctly or you wouldn't be here. What is it doing?
– WhozCraig
Nov 10 at 14:00






1




1




It is a bubble sort. And the loop conditions in looper are suspicious.
– Nelfeal
Nov 10 at 14:01




It is a bubble sort. And the loop conditions in looper are suspicious.
– Nelfeal
Nov 10 at 14:01












@Nelfeal can you please help me out with the code? What changes would you do?
– Debojeet Das
Nov 10 at 14:04






@Nelfeal can you please help me out with the code? What changes would you do?
– Debojeet Das
Nov 10 at 14:04






1




1




Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
– Nelfeal
Nov 10 at 14:13






Actually I misread the sort call; it's not really a bubble sort. It's not really anything I know in fact. I think you meant to write sort(p+j+1, p+j).
– Nelfeal
Nov 10 at 14:13














@Nelfeal Sure I understood that reference but for insertion sort what should I do?
– Debojeet Das
Nov 10 at 14:25




@Nelfeal Sure I understood that reference but for insertion sort what should I do?
– Debojeet Das
Nov 10 at 14:25












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










Your current method is ... not quite right, for any kind of sort. Insertion sort would take an element and insert it at the correct index, then shift the already inserted items down appropriately. Something like



void looper(int *p)
{
for (int i = 1;i < 25;i++)
{
int key = p[i];
int j = i - 1;
while (j >= 0 && p[j] > key)
{
p[j + 1] = p[j];
j = j - 1;
}
p[j + 1] = key;
}
}





share|improve this answer






























    up vote
    0
    down vote













    Insertion sort is about building a sorted segment, and while doing so, using the fact it is sorted to optimally perform a binary search if the list representation supports random access (and your array does) for the location of the next element (which could go at the beginning, the end, or anywhere in between) . If it goes anywhere besides the position it is already in, shifting is going to happen. To place the incoming element, do the following:




    1. Search the already sorted segment to find the location of the incoming value.

    2. Once you find the spot it is supposed to be inserted, loop over the segment from there through the end of the sorted segment, continually swapping with the slot of the incoming element. When this is done, all of the elements up to then will be sorted.

    3. This process repeats for each element


    An example would be best



    5 3 8 1

    Active element: 5
    Length of sorted segment: 0


    Starting with a sorted segment of zero length, not much happens. the first element is already "sorted" and we can move on to the next.





    5 3 8 1

    Active element: 3
    Length of sorted segment: 1


    At this time we do a search of the sorted segment. We find that 3 belongs at the beginning of the segment. So we swap element pairs arr[0] and arr[1]. When finished, we now have a sorted segment of length 2.





    3 5 8 1

    Active element: 8
    Length of sorted segment: 2


    Again, search the sorted segment an we'll discover the element belongs on the end. but that's where it already is, so no swaps will take place and we can move on.





    3 5 8 1

    Active element: 1
    Length of sorted segment: 3


    This final element amplifies the general algorithm nicely. The 1 belongs where the 3 is, and everything should be shifted up accordingly. One way to do that is to loop up the sorted segment, starting at the insertion point (where 3 is) up through the end of the sorted segment, continually swapping the loop-indexed element with the active element slot (in this case, the last slot). The results after each swap will look like this:



    3 5 8 1
    ^-----^

    1 5 8 3
    ^---^

    1 3 8 5
    ^-^

    1 3 5 8




    That's it. In code, it looks something like this:



    #include <stdio.h>
    #include <stdlib.h>

    void swap_int(int *a, int *b)
    {
    int tmp = *a;
    *a = *b;
    *b = tmp;
    }

    const int *binary_search(int value, const int arr, size_t len)
    {
    if (len == 0)
    return arr;

    size_t mid = len / 2;

    if (value < arr[mid])
    return binary_search(value, arr, mid);

    return binary_search(value, arr + mid + 1, len - len / 2 - 1);

    }

    void insertion_sort(int arr, size_t len)
    {
    for (size_t i = 0; i < len; ++i)
    {
    size_t pos = binary_search(arr[i], arr, i) - arr;
    for (size_t j = pos; j < i; ++j)
    swap_int(arr + i, arr + j);
    }
    }

    int main()
    {
    int arr = { 5,3,8,6,9,2,4,1,7 };

    for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
    printf("%d ", arr[i]);
    fputc('n', stdout);

    insertion_sort(arr, sizeof arr / sizeof *arr);

    for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
    printf("%d ", arr[i]);
    fputc('n', stdout);
    }


    Output



    5 3 8 6 9 2 4 1 7
    1 2 3 4 5 6 7 8 9





    share|improve this answer




























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote



      accepted










      Your current method is ... not quite right, for any kind of sort. Insertion sort would take an element and insert it at the correct index, then shift the already inserted items down appropriately. Something like



      void looper(int *p)
      {
      for (int i = 1;i < 25;i++)
      {
      int key = p[i];
      int j = i - 1;
      while (j >= 0 && p[j] > key)
      {
      p[j + 1] = p[j];
      j = j - 1;
      }
      p[j + 1] = key;
      }
      }





      share|improve this answer



























        up vote
        0
        down vote



        accepted










        Your current method is ... not quite right, for any kind of sort. Insertion sort would take an element and insert it at the correct index, then shift the already inserted items down appropriately. Something like



        void looper(int *p)
        {
        for (int i = 1;i < 25;i++)
        {
        int key = p[i];
        int j = i - 1;
        while (j >= 0 && p[j] > key)
        {
        p[j + 1] = p[j];
        j = j - 1;
        }
        p[j + 1] = key;
        }
        }





        share|improve this answer

























          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          Your current method is ... not quite right, for any kind of sort. Insertion sort would take an element and insert it at the correct index, then shift the already inserted items down appropriately. Something like



          void looper(int *p)
          {
          for (int i = 1;i < 25;i++)
          {
          int key = p[i];
          int j = i - 1;
          while (j >= 0 && p[j] > key)
          {
          p[j + 1] = p[j];
          j = j - 1;
          }
          p[j + 1] = key;
          }
          }





          share|improve this answer














          Your current method is ... not quite right, for any kind of sort. Insertion sort would take an element and insert it at the correct index, then shift the already inserted items down appropriately. Something like



          void looper(int *p)
          {
          for (int i = 1;i < 25;i++)
          {
          int key = p[i];
          int j = i - 1;
          while (j >= 0 && p[j] > key)
          {
          p[j + 1] = p[j];
          j = j - 1;
          }
          p[j + 1] = key;
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 4:04

























          answered Nov 10 at 14:29









          BurnsBA

          1,5541220




          1,5541220
























              up vote
              0
              down vote













              Insertion sort is about building a sorted segment, and while doing so, using the fact it is sorted to optimally perform a binary search if the list representation supports random access (and your array does) for the location of the next element (which could go at the beginning, the end, or anywhere in between) . If it goes anywhere besides the position it is already in, shifting is going to happen. To place the incoming element, do the following:




              1. Search the already sorted segment to find the location of the incoming value.

              2. Once you find the spot it is supposed to be inserted, loop over the segment from there through the end of the sorted segment, continually swapping with the slot of the incoming element. When this is done, all of the elements up to then will be sorted.

              3. This process repeats for each element


              An example would be best



              5 3 8 1

              Active element: 5
              Length of sorted segment: 0


              Starting with a sorted segment of zero length, not much happens. the first element is already "sorted" and we can move on to the next.





              5 3 8 1

              Active element: 3
              Length of sorted segment: 1


              At this time we do a search of the sorted segment. We find that 3 belongs at the beginning of the segment. So we swap element pairs arr[0] and arr[1]. When finished, we now have a sorted segment of length 2.





              3 5 8 1

              Active element: 8
              Length of sorted segment: 2


              Again, search the sorted segment an we'll discover the element belongs on the end. but that's where it already is, so no swaps will take place and we can move on.





              3 5 8 1

              Active element: 1
              Length of sorted segment: 3


              This final element amplifies the general algorithm nicely. The 1 belongs where the 3 is, and everything should be shifted up accordingly. One way to do that is to loop up the sorted segment, starting at the insertion point (where 3 is) up through the end of the sorted segment, continually swapping the loop-indexed element with the active element slot (in this case, the last slot). The results after each swap will look like this:



              3 5 8 1
              ^-----^

              1 5 8 3
              ^---^

              1 3 8 5
              ^-^

              1 3 5 8




              That's it. In code, it looks something like this:



              #include <stdio.h>
              #include <stdlib.h>

              void swap_int(int *a, int *b)
              {
              int tmp = *a;
              *a = *b;
              *b = tmp;
              }

              const int *binary_search(int value, const int arr, size_t len)
              {
              if (len == 0)
              return arr;

              size_t mid = len / 2;

              if (value < arr[mid])
              return binary_search(value, arr, mid);

              return binary_search(value, arr + mid + 1, len - len / 2 - 1);

              }

              void insertion_sort(int arr, size_t len)
              {
              for (size_t i = 0; i < len; ++i)
              {
              size_t pos = binary_search(arr[i], arr, i) - arr;
              for (size_t j = pos; j < i; ++j)
              swap_int(arr + i, arr + j);
              }
              }

              int main()
              {
              int arr = { 5,3,8,6,9,2,4,1,7 };

              for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
              printf("%d ", arr[i]);
              fputc('n', stdout);

              insertion_sort(arr, sizeof arr / sizeof *arr);

              for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
              printf("%d ", arr[i]);
              fputc('n', stdout);
              }


              Output



              5 3 8 6 9 2 4 1 7
              1 2 3 4 5 6 7 8 9





              share|improve this answer

























                up vote
                0
                down vote













                Insertion sort is about building a sorted segment, and while doing so, using the fact it is sorted to optimally perform a binary search if the list representation supports random access (and your array does) for the location of the next element (which could go at the beginning, the end, or anywhere in between) . If it goes anywhere besides the position it is already in, shifting is going to happen. To place the incoming element, do the following:




                1. Search the already sorted segment to find the location of the incoming value.

                2. Once you find the spot it is supposed to be inserted, loop over the segment from there through the end of the sorted segment, continually swapping with the slot of the incoming element. When this is done, all of the elements up to then will be sorted.

                3. This process repeats for each element


                An example would be best



                5 3 8 1

                Active element: 5
                Length of sorted segment: 0


                Starting with a sorted segment of zero length, not much happens. the first element is already "sorted" and we can move on to the next.





                5 3 8 1

                Active element: 3
                Length of sorted segment: 1


                At this time we do a search of the sorted segment. We find that 3 belongs at the beginning of the segment. So we swap element pairs arr[0] and arr[1]. When finished, we now have a sorted segment of length 2.





                3 5 8 1

                Active element: 8
                Length of sorted segment: 2


                Again, search the sorted segment an we'll discover the element belongs on the end. but that's where it already is, so no swaps will take place and we can move on.





                3 5 8 1

                Active element: 1
                Length of sorted segment: 3


                This final element amplifies the general algorithm nicely. The 1 belongs where the 3 is, and everything should be shifted up accordingly. One way to do that is to loop up the sorted segment, starting at the insertion point (where 3 is) up through the end of the sorted segment, continually swapping the loop-indexed element with the active element slot (in this case, the last slot). The results after each swap will look like this:



                3 5 8 1
                ^-----^

                1 5 8 3
                ^---^

                1 3 8 5
                ^-^

                1 3 5 8




                That's it. In code, it looks something like this:



                #include <stdio.h>
                #include <stdlib.h>

                void swap_int(int *a, int *b)
                {
                int tmp = *a;
                *a = *b;
                *b = tmp;
                }

                const int *binary_search(int value, const int arr, size_t len)
                {
                if (len == 0)
                return arr;

                size_t mid = len / 2;

                if (value < arr[mid])
                return binary_search(value, arr, mid);

                return binary_search(value, arr + mid + 1, len - len / 2 - 1);

                }

                void insertion_sort(int arr, size_t len)
                {
                for (size_t i = 0; i < len; ++i)
                {
                size_t pos = binary_search(arr[i], arr, i) - arr;
                for (size_t j = pos; j < i; ++j)
                swap_int(arr + i, arr + j);
                }
                }

                int main()
                {
                int arr = { 5,3,8,6,9,2,4,1,7 };

                for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                printf("%d ", arr[i]);
                fputc('n', stdout);

                insertion_sort(arr, sizeof arr / sizeof *arr);

                for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                printf("%d ", arr[i]);
                fputc('n', stdout);
                }


                Output



                5 3 8 6 9 2 4 1 7
                1 2 3 4 5 6 7 8 9





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Insertion sort is about building a sorted segment, and while doing so, using the fact it is sorted to optimally perform a binary search if the list representation supports random access (and your array does) for the location of the next element (which could go at the beginning, the end, or anywhere in between) . If it goes anywhere besides the position it is already in, shifting is going to happen. To place the incoming element, do the following:




                  1. Search the already sorted segment to find the location of the incoming value.

                  2. Once you find the spot it is supposed to be inserted, loop over the segment from there through the end of the sorted segment, continually swapping with the slot of the incoming element. When this is done, all of the elements up to then will be sorted.

                  3. This process repeats for each element


                  An example would be best



                  5 3 8 1

                  Active element: 5
                  Length of sorted segment: 0


                  Starting with a sorted segment of zero length, not much happens. the first element is already "sorted" and we can move on to the next.





                  5 3 8 1

                  Active element: 3
                  Length of sorted segment: 1


                  At this time we do a search of the sorted segment. We find that 3 belongs at the beginning of the segment. So we swap element pairs arr[0] and arr[1]. When finished, we now have a sorted segment of length 2.





                  3 5 8 1

                  Active element: 8
                  Length of sorted segment: 2


                  Again, search the sorted segment an we'll discover the element belongs on the end. but that's where it already is, so no swaps will take place and we can move on.





                  3 5 8 1

                  Active element: 1
                  Length of sorted segment: 3


                  This final element amplifies the general algorithm nicely. The 1 belongs where the 3 is, and everything should be shifted up accordingly. One way to do that is to loop up the sorted segment, starting at the insertion point (where 3 is) up through the end of the sorted segment, continually swapping the loop-indexed element with the active element slot (in this case, the last slot). The results after each swap will look like this:



                  3 5 8 1
                  ^-----^

                  1 5 8 3
                  ^---^

                  1 3 8 5
                  ^-^

                  1 3 5 8




                  That's it. In code, it looks something like this:



                  #include <stdio.h>
                  #include <stdlib.h>

                  void swap_int(int *a, int *b)
                  {
                  int tmp = *a;
                  *a = *b;
                  *b = tmp;
                  }

                  const int *binary_search(int value, const int arr, size_t len)
                  {
                  if (len == 0)
                  return arr;

                  size_t mid = len / 2;

                  if (value < arr[mid])
                  return binary_search(value, arr, mid);

                  return binary_search(value, arr + mid + 1, len - len / 2 - 1);

                  }

                  void insertion_sort(int arr, size_t len)
                  {
                  for (size_t i = 0; i < len; ++i)
                  {
                  size_t pos = binary_search(arr[i], arr, i) - arr;
                  for (size_t j = pos; j < i; ++j)
                  swap_int(arr + i, arr + j);
                  }
                  }

                  int main()
                  {
                  int arr = { 5,3,8,6,9,2,4,1,7 };

                  for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                  printf("%d ", arr[i]);
                  fputc('n', stdout);

                  insertion_sort(arr, sizeof arr / sizeof *arr);

                  for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                  printf("%d ", arr[i]);
                  fputc('n', stdout);
                  }


                  Output



                  5 3 8 6 9 2 4 1 7
                  1 2 3 4 5 6 7 8 9





                  share|improve this answer












                  Insertion sort is about building a sorted segment, and while doing so, using the fact it is sorted to optimally perform a binary search if the list representation supports random access (and your array does) for the location of the next element (which could go at the beginning, the end, or anywhere in between) . If it goes anywhere besides the position it is already in, shifting is going to happen. To place the incoming element, do the following:




                  1. Search the already sorted segment to find the location of the incoming value.

                  2. Once you find the spot it is supposed to be inserted, loop over the segment from there through the end of the sorted segment, continually swapping with the slot of the incoming element. When this is done, all of the elements up to then will be sorted.

                  3. This process repeats for each element


                  An example would be best



                  5 3 8 1

                  Active element: 5
                  Length of sorted segment: 0


                  Starting with a sorted segment of zero length, not much happens. the first element is already "sorted" and we can move on to the next.





                  5 3 8 1

                  Active element: 3
                  Length of sorted segment: 1


                  At this time we do a search of the sorted segment. We find that 3 belongs at the beginning of the segment. So we swap element pairs arr[0] and arr[1]. When finished, we now have a sorted segment of length 2.





                  3 5 8 1

                  Active element: 8
                  Length of sorted segment: 2


                  Again, search the sorted segment an we'll discover the element belongs on the end. but that's where it already is, so no swaps will take place and we can move on.





                  3 5 8 1

                  Active element: 1
                  Length of sorted segment: 3


                  This final element amplifies the general algorithm nicely. The 1 belongs where the 3 is, and everything should be shifted up accordingly. One way to do that is to loop up the sorted segment, starting at the insertion point (where 3 is) up through the end of the sorted segment, continually swapping the loop-indexed element with the active element slot (in this case, the last slot). The results after each swap will look like this:



                  3 5 8 1
                  ^-----^

                  1 5 8 3
                  ^---^

                  1 3 8 5
                  ^-^

                  1 3 5 8




                  That's it. In code, it looks something like this:



                  #include <stdio.h>
                  #include <stdlib.h>

                  void swap_int(int *a, int *b)
                  {
                  int tmp = *a;
                  *a = *b;
                  *b = tmp;
                  }

                  const int *binary_search(int value, const int arr, size_t len)
                  {
                  if (len == 0)
                  return arr;

                  size_t mid = len / 2;

                  if (value < arr[mid])
                  return binary_search(value, arr, mid);

                  return binary_search(value, arr + mid + 1, len - len / 2 - 1);

                  }

                  void insertion_sort(int arr, size_t len)
                  {
                  for (size_t i = 0; i < len; ++i)
                  {
                  size_t pos = binary_search(arr[i], arr, i) - arr;
                  for (size_t j = pos; j < i; ++j)
                  swap_int(arr + i, arr + j);
                  }
                  }

                  int main()
                  {
                  int arr = { 5,3,8,6,9,2,4,1,7 };

                  for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                  printf("%d ", arr[i]);
                  fputc('n', stdout);

                  insertion_sort(arr, sizeof arr / sizeof *arr);

                  for (size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
                  printf("%d ", arr[i]);
                  fputc('n', stdout);
                  }


                  Output



                  5 3 8 6 9 2 4 1 7
                  1 2 3 4 5 6 7 8 9






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 15:07









                  WhozCraig

                  50.7k858104




                  50.7k858104















                      Popular posts from this blog

                      Florida Star v. B. J. F.

                      Error while running script in elastic search , gateway timeout

                      Adding quotations to stringified JSON object values