Are there any cases where this particular sorting algorithm would not work?












1















Basically, I was wondering if there are any possible logic errors that could occur when implementing the following code to perform an insertion sort. I noticed that some examples use a while loop with the logical AND operator, but I think I can achieve the same output by using a flag to monitor whether any of the values in the sorted list are smaller than the the current index of the unsorted list, and by storing the position of that smaller value.



#include<stdio.h>
void insertion(int size, int[*]);
int main()
{
int size;
printf("Size of Array: ");
scanf("%d",&size);
int ary[size];
for(int i=0; i<size; i++)
scanf("%d",&ary[i]);
insertion(size, ary);
return 0;
}
void insertion(int size, int A[size])
{
int value;
int hole;
int flag;

for(int i=1; i<size; i++)
{
value = A[i];//the value of the current index of the unsorted list
//gets stored in variable named value
flag = 0;
for(int j=i-1; j>=0; j--)
{
if(A[j]>value)
{
flag = 1;
hole = j; //index position where value will be
//inserted into
A[j+1] = A[j];
}
}
if(flag) //ensures that insertion occurs only when one of the
//sorted elements is less than value
A[hole] = value;
}

for(int i=0; i<size; i++)
printf("%d ",A[i]);
}


`



This following method is the alternate variation that uses a while loop instead of a flag:



void unshuffle( int size, int* A )
{
int value;
int position;

for( int i=1; i<size; i++ )
{
value = A[i];
position = i;

while( A[position-1]>value && position>0 )
{
A[position] = A[position-1];
position--;
}
A[position] = value;
}

}


Is this the preferred method for writing an insertion sort in terms of efficiency?










share|improve this question




















  • 2





    If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

    – chux
    Nov 16 '18 at 6:15













  • I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

    – Nicholas Cousar
    Nov 16 '18 at 20:37






  • 1





    Nicholas Cousar: insure you are not using tabs

    – chux
    Nov 17 '18 at 0:17
















1















Basically, I was wondering if there are any possible logic errors that could occur when implementing the following code to perform an insertion sort. I noticed that some examples use a while loop with the logical AND operator, but I think I can achieve the same output by using a flag to monitor whether any of the values in the sorted list are smaller than the the current index of the unsorted list, and by storing the position of that smaller value.



#include<stdio.h>
void insertion(int size, int[*]);
int main()
{
int size;
printf("Size of Array: ");
scanf("%d",&size);
int ary[size];
for(int i=0; i<size; i++)
scanf("%d",&ary[i]);
insertion(size, ary);
return 0;
}
void insertion(int size, int A[size])
{
int value;
int hole;
int flag;

for(int i=1; i<size; i++)
{
value = A[i];//the value of the current index of the unsorted list
//gets stored in variable named value
flag = 0;
for(int j=i-1; j>=0; j--)
{
if(A[j]>value)
{
flag = 1;
hole = j; //index position where value will be
//inserted into
A[j+1] = A[j];
}
}
if(flag) //ensures that insertion occurs only when one of the
//sorted elements is less than value
A[hole] = value;
}

for(int i=0; i<size; i++)
printf("%d ",A[i]);
}


`



This following method is the alternate variation that uses a while loop instead of a flag:



void unshuffle( int size, int* A )
{
int value;
int position;

for( int i=1; i<size; i++ )
{
value = A[i];
position = i;

while( A[position-1]>value && position>0 )
{
A[position] = A[position-1];
position--;
}
A[position] = value;
}

}


Is this the preferred method for writing an insertion sort in terms of efficiency?










share|improve this question




















  • 2





    If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

    – chux
    Nov 16 '18 at 6:15













  • I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

    – Nicholas Cousar
    Nov 16 '18 at 20:37






  • 1





    Nicholas Cousar: insure you are not using tabs

    – chux
    Nov 17 '18 at 0:17














1












1








1








Basically, I was wondering if there are any possible logic errors that could occur when implementing the following code to perform an insertion sort. I noticed that some examples use a while loop with the logical AND operator, but I think I can achieve the same output by using a flag to monitor whether any of the values in the sorted list are smaller than the the current index of the unsorted list, and by storing the position of that smaller value.



#include<stdio.h>
void insertion(int size, int[*]);
int main()
{
int size;
printf("Size of Array: ");
scanf("%d",&size);
int ary[size];
for(int i=0; i<size; i++)
scanf("%d",&ary[i]);
insertion(size, ary);
return 0;
}
void insertion(int size, int A[size])
{
int value;
int hole;
int flag;

for(int i=1; i<size; i++)
{
value = A[i];//the value of the current index of the unsorted list
//gets stored in variable named value
flag = 0;
for(int j=i-1; j>=0; j--)
{
if(A[j]>value)
{
flag = 1;
hole = j; //index position where value will be
//inserted into
A[j+1] = A[j];
}
}
if(flag) //ensures that insertion occurs only when one of the
//sorted elements is less than value
A[hole] = value;
}

for(int i=0; i<size; i++)
printf("%d ",A[i]);
}


`



This following method is the alternate variation that uses a while loop instead of a flag:



void unshuffle( int size, int* A )
{
int value;
int position;

for( int i=1; i<size; i++ )
{
value = A[i];
position = i;

while( A[position-1]>value && position>0 )
{
A[position] = A[position-1];
position--;
}
A[position] = value;
}

}


Is this the preferred method for writing an insertion sort in terms of efficiency?










share|improve this question
















Basically, I was wondering if there are any possible logic errors that could occur when implementing the following code to perform an insertion sort. I noticed that some examples use a while loop with the logical AND operator, but I think I can achieve the same output by using a flag to monitor whether any of the values in the sorted list are smaller than the the current index of the unsorted list, and by storing the position of that smaller value.



#include<stdio.h>
void insertion(int size, int[*]);
int main()
{
int size;
printf("Size of Array: ");
scanf("%d",&size);
int ary[size];
for(int i=0; i<size; i++)
scanf("%d",&ary[i]);
insertion(size, ary);
return 0;
}
void insertion(int size, int A[size])
{
int value;
int hole;
int flag;

for(int i=1; i<size; i++)
{
value = A[i];//the value of the current index of the unsorted list
//gets stored in variable named value
flag = 0;
for(int j=i-1; j>=0; j--)
{
if(A[j]>value)
{
flag = 1;
hole = j; //index position where value will be
//inserted into
A[j+1] = A[j];
}
}
if(flag) //ensures that insertion occurs only when one of the
//sorted elements is less than value
A[hole] = value;
}

for(int i=0; i<size; i++)
printf("%d ",A[i]);
}


`



This following method is the alternate variation that uses a while loop instead of a flag:



void unshuffle( int size, int* A )
{
int value;
int position;

for( int i=1; i<size; i++ )
{
value = A[i];
position = i;

while( A[position-1]>value && position>0 )
{
A[position] = A[position-1];
position--;
}
A[position] = value;
}

}


Is this the preferred method for writing an insertion sort in terms of efficiency?







c logic insertion-sort






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 20:50







Nicholas Cousar

















asked Nov 16 '18 at 5:57









Nicholas CousarNicholas Cousar

1405




1405








  • 2





    If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

    – chux
    Nov 16 '18 at 6:15













  • I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

    – Nicholas Cousar
    Nov 16 '18 at 20:37






  • 1





    Nicholas Cousar: insure you are not using tabs

    – chux
    Nov 17 '18 at 0:17














  • 2





    If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

    – chux
    Nov 16 '18 at 6:15













  • I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

    – Nicholas Cousar
    Nov 16 '18 at 20:37






  • 1





    Nicholas Cousar: insure you are not using tabs

    – chux
    Nov 17 '18 at 0:17








2




2





If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

– chux
Nov 16 '18 at 6:15







If its working code, consider codereview.stackexchange.com for a deeper review. See How to get the best value out of Code Review. Note code would improve with better formatting. Research your development environment's auto-formatter.

– chux
Nov 16 '18 at 6:15















I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

– Nicholas Cousar
Nov 16 '18 at 20:37





I agree this formatting is sloppy, but I can't figure out how to copy and paste my cleanly auto-formatted code into a stackoverflow submission without losing some of the formatting. Some lines get pasted correctly while others are not recognized as code until I indent them, which ultimately makes everything look lopsided and messy. Any tips on how to copy/paste code on this site in one fell swoop, while still preserving the original formatting?

– Nicholas Cousar
Nov 16 '18 at 20:37




1




1





Nicholas Cousar: insure you are not using tabs

– chux
Nov 17 '18 at 0:17





Nicholas Cousar: insure you are not using tabs

– chux
Nov 17 '18 at 0:17












1 Answer
1






active

oldest

votes


















3














You are getting less efficient with your approach; consider following variant of your algorithm:



for(int j=i-1; j>=0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
A[j+1] = value; // worst that could happen: self asignment;
// still less costly than another `if`!

break; // you're in the sorted part of the array, so all other
// values are smaller or equal as well -> can exit!
}
}


Now you don't need the flag/hole any more, but more important, you don't needlessly iterate over the already sorted smaller part any more.



The same you'd achieve with the double condition in the while loop you started from...



Actually, there's an error in, if the current element is smaller than all already sorted ones, the else clause is never entered, so the element won't be inserted at first location. Fix is easy, though:



int j;
for(j = i-1; j >= 0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
break;
}
}
A[j+1] = value; // (still self-assignment possible)
// if j got -1: insert at 0, so fine


Now we got even closer to the original while loop...



Still you are trying to optimise an algorithm that is well known for its inefficiency (average(!) runtime of O(n²)), I don't consider it worth to care for such one that much, better switch to quick-sort right from start (O(n log(n)) average runtime), heap-sort (with maximum O(n log(n)) runtime, but worse constants than quicksort) or intro-sort (hybrid of first two, standard sorting algorithm of C++ std::sort in most implementations).






share|improve this answer


























  • Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

    – Nicholas Cousar
    Nov 16 '18 at 21:20











  • @NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

    – Aconcagua
    Nov 17 '18 at 1:06











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53332225%2fare-there-any-cases-where-this-particular-sorting-algorithm-would-not-work%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














You are getting less efficient with your approach; consider following variant of your algorithm:



for(int j=i-1; j>=0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
A[j+1] = value; // worst that could happen: self asignment;
// still less costly than another `if`!

break; // you're in the sorted part of the array, so all other
// values are smaller or equal as well -> can exit!
}
}


Now you don't need the flag/hole any more, but more important, you don't needlessly iterate over the already sorted smaller part any more.



The same you'd achieve with the double condition in the while loop you started from...



Actually, there's an error in, if the current element is smaller than all already sorted ones, the else clause is never entered, so the element won't be inserted at first location. Fix is easy, though:



int j;
for(j = i-1; j >= 0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
break;
}
}
A[j+1] = value; // (still self-assignment possible)
// if j got -1: insert at 0, so fine


Now we got even closer to the original while loop...



Still you are trying to optimise an algorithm that is well known for its inefficiency (average(!) runtime of O(n²)), I don't consider it worth to care for such one that much, better switch to quick-sort right from start (O(n log(n)) average runtime), heap-sort (with maximum O(n log(n)) runtime, but worse constants than quicksort) or intro-sort (hybrid of first two, standard sorting algorithm of C++ std::sort in most implementations).






share|improve this answer


























  • Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

    – Nicholas Cousar
    Nov 16 '18 at 21:20











  • @NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

    – Aconcagua
    Nov 17 '18 at 1:06
















3














You are getting less efficient with your approach; consider following variant of your algorithm:



for(int j=i-1; j>=0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
A[j+1] = value; // worst that could happen: self asignment;
// still less costly than another `if`!

break; // you're in the sorted part of the array, so all other
// values are smaller or equal as well -> can exit!
}
}


Now you don't need the flag/hole any more, but more important, you don't needlessly iterate over the already sorted smaller part any more.



The same you'd achieve with the double condition in the while loop you started from...



Actually, there's an error in, if the current element is smaller than all already sorted ones, the else clause is never entered, so the element won't be inserted at first location. Fix is easy, though:



int j;
for(j = i-1; j >= 0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
break;
}
}
A[j+1] = value; // (still self-assignment possible)
// if j got -1: insert at 0, so fine


Now we got even closer to the original while loop...



Still you are trying to optimise an algorithm that is well known for its inefficiency (average(!) runtime of O(n²)), I don't consider it worth to care for such one that much, better switch to quick-sort right from start (O(n log(n)) average runtime), heap-sort (with maximum O(n log(n)) runtime, but worse constants than quicksort) or intro-sort (hybrid of first two, standard sorting algorithm of C++ std::sort in most implementations).






share|improve this answer


























  • Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

    – Nicholas Cousar
    Nov 16 '18 at 21:20











  • @NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

    – Aconcagua
    Nov 17 '18 at 1:06














3












3








3







You are getting less efficient with your approach; consider following variant of your algorithm:



for(int j=i-1; j>=0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
A[j+1] = value; // worst that could happen: self asignment;
// still less costly than another `if`!

break; // you're in the sorted part of the array, so all other
// values are smaller or equal as well -> can exit!
}
}


Now you don't need the flag/hole any more, but more important, you don't needlessly iterate over the already sorted smaller part any more.



The same you'd achieve with the double condition in the while loop you started from...



Actually, there's an error in, if the current element is smaller than all already sorted ones, the else clause is never entered, so the element won't be inserted at first location. Fix is easy, though:



int j;
for(j = i-1; j >= 0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
break;
}
}
A[j+1] = value; // (still self-assignment possible)
// if j got -1: insert at 0, so fine


Now we got even closer to the original while loop...



Still you are trying to optimise an algorithm that is well known for its inefficiency (average(!) runtime of O(n²)), I don't consider it worth to care for such one that much, better switch to quick-sort right from start (O(n log(n)) average runtime), heap-sort (with maximum O(n log(n)) runtime, but worse constants than quicksort) or intro-sort (hybrid of first two, standard sorting algorithm of C++ std::sort in most implementations).






share|improve this answer















You are getting less efficient with your approach; consider following variant of your algorithm:



for(int j=i-1; j>=0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
A[j+1] = value; // worst that could happen: self asignment;
// still less costly than another `if`!

break; // you're in the sorted part of the array, so all other
// values are smaller or equal as well -> can exit!
}
}


Now you don't need the flag/hole any more, but more important, you don't needlessly iterate over the already sorted smaller part any more.



The same you'd achieve with the double condition in the while loop you started from...



Actually, there's an error in, if the current element is smaller than all already sorted ones, the else clause is never entered, so the element won't be inserted at first location. Fix is easy, though:



int j;
for(j = i-1; j >= 0; j--)
{
if(A[j] > value)
{
A[j+1] = A[j];
}
else
{
break;
}
}
A[j+1] = value; // (still self-assignment possible)
// if j got -1: insert at 0, so fine


Now we got even closer to the original while loop...



Still you are trying to optimise an algorithm that is well known for its inefficiency (average(!) runtime of O(n²)), I don't consider it worth to care for such one that much, better switch to quick-sort right from start (O(n log(n)) average runtime), heap-sort (with maximum O(n log(n)) runtime, but worse constants than quicksort) or intro-sort (hybrid of first two, standard sorting algorithm of C++ std::sort in most implementations).







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 17 '18 at 1:07

























answered Nov 16 '18 at 6:25









AconcaguaAconcagua

12.8k32144




12.8k32144













  • Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

    – Nicholas Cousar
    Nov 16 '18 at 21:20











  • @NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

    – Aconcagua
    Nov 17 '18 at 1:06



















  • Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

    – Nicholas Cousar
    Nov 16 '18 at 21:20











  • @NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

    – Aconcagua
    Nov 17 '18 at 1:06

















Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

– Nicholas Cousar
Nov 16 '18 at 21:20





Wouldn't I still need to include a variable in the first block of the if statement to store the position of the jth index? That way, when the inner loop terminates the program will know where to store value to be inserted? Or are you assuming that I was including such a statement, and that's why the worst case of a self-assignment could occur?

– Nicholas Cousar
Nov 16 '18 at 21:20













@NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

– Aconcagua
Nov 17 '18 at 1:06





@NicholasCousar Yes and no... There was a corner case not handled, to fix, you need access to the loop variable itself outside the loop - but no additional one - see edited answer.

– Aconcagua
Nov 17 '18 at 1:06




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53332225%2fare-there-any-cases-where-this-particular-sorting-algorithm-would-not-work%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly