Can a selection sort algorithm terminate from its loop early the way a bubble sort is able to?












0















This program will run fine if I do not include the early termination flag, but it only needs 10 sort passes to fully sort the list, not the full 12. However, when the termination flag is included, it terminates the sorting too early. Following the logic, I can see that this happens because after the third pass the array is ordered like this:
enter image description here



with the index i currently at 7, there are no lesser values to swap it with, so the flag does not get a value of 1 assigned to it and the loop terminates. So I guess my question is, is it possible to break out of a selection sort algorithm early and still fully complete the sort?



#include<stdio.h>
int main()
{
int list[13]= {23,8,4,7,22,18,39,42,5,88,16,11,3};
int temp,min,flag;
printf( "Before Sortingn" );
printf( "23 8 4 7 22 18 39 42 5 88 16 11 3n" );

for( int i=0; i<12; i++ )
{
flag = 0;
min = i;

for( int j=i+1; j<13; j++ )
{
if( list[j]<list[min] )
{
flag = 1;
min = j ;
}
}

if( !flag )
break;

temp = list[i];
list[i]=list[min];
list[min]=temp;

printf( "nAfter Pass %d.n",i+1 );
for( int i=0; i<13; i++ )
printf( "%d ",list[i] );

printf( "n" );
}

return 0;
}









share|improve this question


















  • 1





    You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

    – 500 - Internal Server Error
    Nov 15 '18 at 20:57






  • 2





    Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

    – paddy
    Nov 15 '18 at 21:02











  • The only thing that you can skip, in a selection sort, is the swap.

    – Tim Randall
    Nov 15 '18 at 21:09


















0















This program will run fine if I do not include the early termination flag, but it only needs 10 sort passes to fully sort the list, not the full 12. However, when the termination flag is included, it terminates the sorting too early. Following the logic, I can see that this happens because after the third pass the array is ordered like this:
enter image description here



with the index i currently at 7, there are no lesser values to swap it with, so the flag does not get a value of 1 assigned to it and the loop terminates. So I guess my question is, is it possible to break out of a selection sort algorithm early and still fully complete the sort?



#include<stdio.h>
int main()
{
int list[13]= {23,8,4,7,22,18,39,42,5,88,16,11,3};
int temp,min,flag;
printf( "Before Sortingn" );
printf( "23 8 4 7 22 18 39 42 5 88 16 11 3n" );

for( int i=0; i<12; i++ )
{
flag = 0;
min = i;

for( int j=i+1; j<13; j++ )
{
if( list[j]<list[min] )
{
flag = 1;
min = j ;
}
}

if( !flag )
break;

temp = list[i];
list[i]=list[min];
list[min]=temp;

printf( "nAfter Pass %d.n",i+1 );
for( int i=0; i<13; i++ )
printf( "%d ",list[i] );

printf( "n" );
}

return 0;
}









share|improve this question


















  • 1





    You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

    – 500 - Internal Server Error
    Nov 15 '18 at 20:57






  • 2





    Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

    – paddy
    Nov 15 '18 at 21:02











  • The only thing that you can skip, in a selection sort, is the swap.

    – Tim Randall
    Nov 15 '18 at 21:09
















0












0








0








This program will run fine if I do not include the early termination flag, but it only needs 10 sort passes to fully sort the list, not the full 12. However, when the termination flag is included, it terminates the sorting too early. Following the logic, I can see that this happens because after the third pass the array is ordered like this:
enter image description here



with the index i currently at 7, there are no lesser values to swap it with, so the flag does not get a value of 1 assigned to it and the loop terminates. So I guess my question is, is it possible to break out of a selection sort algorithm early and still fully complete the sort?



#include<stdio.h>
int main()
{
int list[13]= {23,8,4,7,22,18,39,42,5,88,16,11,3};
int temp,min,flag;
printf( "Before Sortingn" );
printf( "23 8 4 7 22 18 39 42 5 88 16 11 3n" );

for( int i=0; i<12; i++ )
{
flag = 0;
min = i;

for( int j=i+1; j<13; j++ )
{
if( list[j]<list[min] )
{
flag = 1;
min = j ;
}
}

if( !flag )
break;

temp = list[i];
list[i]=list[min];
list[min]=temp;

printf( "nAfter Pass %d.n",i+1 );
for( int i=0; i<13; i++ )
printf( "%d ",list[i] );

printf( "n" );
}

return 0;
}









share|improve this question














This program will run fine if I do not include the early termination flag, but it only needs 10 sort passes to fully sort the list, not the full 12. However, when the termination flag is included, it terminates the sorting too early. Following the logic, I can see that this happens because after the third pass the array is ordered like this:
enter image description here



with the index i currently at 7, there are no lesser values to swap it with, so the flag does not get a value of 1 assigned to it and the loop terminates. So I guess my question is, is it possible to break out of a selection sort algorithm early and still fully complete the sort?



#include<stdio.h>
int main()
{
int list[13]= {23,8,4,7,22,18,39,42,5,88,16,11,3};
int temp,min,flag;
printf( "Before Sortingn" );
printf( "23 8 4 7 22 18 39 42 5 88 16 11 3n" );

for( int i=0; i<12; i++ )
{
flag = 0;
min = i;

for( int j=i+1; j<13; j++ )
{
if( list[j]<list[min] )
{
flag = 1;
min = j ;
}
}

if( !flag )
break;

temp = list[i];
list[i]=list[min];
list[min]=temp;

printf( "nAfter Pass %d.n",i+1 );
for( int i=0; i<13; i++ )
printf( "%d ",list[i] );

printf( "n" );
}

return 0;
}






c flags selection-sort






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 20:50









Nicholas CousarNicholas Cousar

1405




1405








  • 1





    You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

    – 500 - Internal Server Error
    Nov 15 '18 at 20:57






  • 2





    Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

    – paddy
    Nov 15 '18 at 21:02











  • The only thing that you can skip, in a selection sort, is the swap.

    – Tim Randall
    Nov 15 '18 at 21:09
















  • 1





    You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

    – 500 - Internal Server Error
    Nov 15 '18 at 20:57






  • 2





    Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

    – paddy
    Nov 15 '18 at 21:02











  • The only thing that you can skip, in a selection sort, is the swap.

    – Tim Randall
    Nov 15 '18 at 21:09










1




1





You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

– 500 - Internal Server Error
Nov 15 '18 at 20:57





You can't break out like this. Here, the current value, 7, is the lowest in the list, so it does (should) not swap with anything, but that doesn't say anything about the remaining file (except that all values are known to be >= 7).

– 500 - Internal Server Error
Nov 15 '18 at 20:57




2




2





Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

– paddy
Nov 15 '18 at 21:02





Rather than try to optimize selection sort, you could look to smarter sorting algorithms with better time complexity.

– paddy
Nov 15 '18 at 21:02













The only thing that you can skip, in a selection sort, is the swap.

– Tim Randall
Nov 15 '18 at 21:09







The only thing that you can skip, in a selection sort, is the swap.

– Tim Randall
Nov 15 '18 at 21:09














2 Answers
2






active

oldest

votes


















2














Indeed you can. Here is such an implementation,



int selsort(int v, int n){

bool sorted = false; // v not known to be sorted
int i = 0; // i smallest elements in place

while(!sorted){
// find min v[i..n-1]
// check if v[i..n-1] is sorted

int j = i+1;
int min = i; // position of minimum of v[i..j-1]
sorted = true; // v[i..j-1] sorted

while(j<n){
if(v[j]<v[min]) min = j; // update min
if(v[j]<v[j-1]) sorted = false; // update sorted
j++;
}

if (!sorted){
// place min v[i..n-1] in v[i]
int aux = v[i];
v[i] = v[min];
v[min] = aux;

i++;
}
}

return EXIT_SUCCESS;
}


As usual, in iteration i we start with v[0..i-1] sorted with the i smallest elements of the array in the correct place. So we want to find the min v[i..n-1] to put in position i. In this variant, as we do that we also check if v[i..n-1] is sorted. If it is sorted then there is nothing else to do.



Your implementation



In your implementation, the way you test for an ordered segment is wrong.



if( list[j]<list[min] )
{
flag = 1;
min = j ;
}


Your flag will stay at 0 as long as you don't have to update the minimum in the inner loop. So any segment with the minimum in the first position will be considered sorted.






share|improve this answer

































    2














    There are almost no redeeming qualities in bubble sort, the nicest thing about it is its name. Donald Knuth has said that




    the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems




    And indeed, from Wikipedia about selection sort:




    Among simple average-case Θ(n²) algorithms, selection sort almost always outperforms bubble sort and gnome sort.




    There is no variation in selection sort - its running time does not depend on the ordering. For another good simple O(n²) algorithm that has variable running time, see insertion sort.






    share|improve this answer























      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%2f53327710%2fcan-a-selection-sort-algorithm-terminate-from-its-loop-early-the-way-a-bubble-so%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Indeed you can. Here is such an implementation,



      int selsort(int v, int n){

      bool sorted = false; // v not known to be sorted
      int i = 0; // i smallest elements in place

      while(!sorted){
      // find min v[i..n-1]
      // check if v[i..n-1] is sorted

      int j = i+1;
      int min = i; // position of minimum of v[i..j-1]
      sorted = true; // v[i..j-1] sorted

      while(j<n){
      if(v[j]<v[min]) min = j; // update min
      if(v[j]<v[j-1]) sorted = false; // update sorted
      j++;
      }

      if (!sorted){
      // place min v[i..n-1] in v[i]
      int aux = v[i];
      v[i] = v[min];
      v[min] = aux;

      i++;
      }
      }

      return EXIT_SUCCESS;
      }


      As usual, in iteration i we start with v[0..i-1] sorted with the i smallest elements of the array in the correct place. So we want to find the min v[i..n-1] to put in position i. In this variant, as we do that we also check if v[i..n-1] is sorted. If it is sorted then there is nothing else to do.



      Your implementation



      In your implementation, the way you test for an ordered segment is wrong.



      if( list[j]<list[min] )
      {
      flag = 1;
      min = j ;
      }


      Your flag will stay at 0 as long as you don't have to update the minimum in the inner loop. So any segment with the minimum in the first position will be considered sorted.






      share|improve this answer






























        2














        Indeed you can. Here is such an implementation,



        int selsort(int v, int n){

        bool sorted = false; // v not known to be sorted
        int i = 0; // i smallest elements in place

        while(!sorted){
        // find min v[i..n-1]
        // check if v[i..n-1] is sorted

        int j = i+1;
        int min = i; // position of minimum of v[i..j-1]
        sorted = true; // v[i..j-1] sorted

        while(j<n){
        if(v[j]<v[min]) min = j; // update min
        if(v[j]<v[j-1]) sorted = false; // update sorted
        j++;
        }

        if (!sorted){
        // place min v[i..n-1] in v[i]
        int aux = v[i];
        v[i] = v[min];
        v[min] = aux;

        i++;
        }
        }

        return EXIT_SUCCESS;
        }


        As usual, in iteration i we start with v[0..i-1] sorted with the i smallest elements of the array in the correct place. So we want to find the min v[i..n-1] to put in position i. In this variant, as we do that we also check if v[i..n-1] is sorted. If it is sorted then there is nothing else to do.



        Your implementation



        In your implementation, the way you test for an ordered segment is wrong.



        if( list[j]<list[min] )
        {
        flag = 1;
        min = j ;
        }


        Your flag will stay at 0 as long as you don't have to update the minimum in the inner loop. So any segment with the minimum in the first position will be considered sorted.






        share|improve this answer




























          2












          2








          2







          Indeed you can. Here is such an implementation,



          int selsort(int v, int n){

          bool sorted = false; // v not known to be sorted
          int i = 0; // i smallest elements in place

          while(!sorted){
          // find min v[i..n-1]
          // check if v[i..n-1] is sorted

          int j = i+1;
          int min = i; // position of minimum of v[i..j-1]
          sorted = true; // v[i..j-1] sorted

          while(j<n){
          if(v[j]<v[min]) min = j; // update min
          if(v[j]<v[j-1]) sorted = false; // update sorted
          j++;
          }

          if (!sorted){
          // place min v[i..n-1] in v[i]
          int aux = v[i];
          v[i] = v[min];
          v[min] = aux;

          i++;
          }
          }

          return EXIT_SUCCESS;
          }


          As usual, in iteration i we start with v[0..i-1] sorted with the i smallest elements of the array in the correct place. So we want to find the min v[i..n-1] to put in position i. In this variant, as we do that we also check if v[i..n-1] is sorted. If it is sorted then there is nothing else to do.



          Your implementation



          In your implementation, the way you test for an ordered segment is wrong.



          if( list[j]<list[min] )
          {
          flag = 1;
          min = j ;
          }


          Your flag will stay at 0 as long as you don't have to update the minimum in the inner loop. So any segment with the minimum in the first position will be considered sorted.






          share|improve this answer















          Indeed you can. Here is such an implementation,



          int selsort(int v, int n){

          bool sorted = false; // v not known to be sorted
          int i = 0; // i smallest elements in place

          while(!sorted){
          // find min v[i..n-1]
          // check if v[i..n-1] is sorted

          int j = i+1;
          int min = i; // position of minimum of v[i..j-1]
          sorted = true; // v[i..j-1] sorted

          while(j<n){
          if(v[j]<v[min]) min = j; // update min
          if(v[j]<v[j-1]) sorted = false; // update sorted
          j++;
          }

          if (!sorted){
          // place min v[i..n-1] in v[i]
          int aux = v[i];
          v[i] = v[min];
          v[min] = aux;

          i++;
          }
          }

          return EXIT_SUCCESS;
          }


          As usual, in iteration i we start with v[0..i-1] sorted with the i smallest elements of the array in the correct place. So we want to find the min v[i..n-1] to put in position i. In this variant, as we do that we also check if v[i..n-1] is sorted. If it is sorted then there is nothing else to do.



          Your implementation



          In your implementation, the way you test for an ordered segment is wrong.



          if( list[j]<list[min] )
          {
          flag = 1;
          min = j ;
          }


          Your flag will stay at 0 as long as you don't have to update the minimum in the inner loop. So any segment with the minimum in the first position will be considered sorted.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 1:17

























          answered Nov 15 '18 at 23:08









          Jorge AdrianoJorge Adriano

          2,219919




          2,219919

























              2














              There are almost no redeeming qualities in bubble sort, the nicest thing about it is its name. Donald Knuth has said that




              the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems




              And indeed, from Wikipedia about selection sort:




              Among simple average-case Θ(n²) algorithms, selection sort almost always outperforms bubble sort and gnome sort.




              There is no variation in selection sort - its running time does not depend on the ordering. For another good simple O(n²) algorithm that has variable running time, see insertion sort.






              share|improve this answer




























                2














                There are almost no redeeming qualities in bubble sort, the nicest thing about it is its name. Donald Knuth has said that




                the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems




                And indeed, from Wikipedia about selection sort:




                Among simple average-case Θ(n²) algorithms, selection sort almost always outperforms bubble sort and gnome sort.




                There is no variation in selection sort - its running time does not depend on the ordering. For another good simple O(n²) algorithm that has variable running time, see insertion sort.






                share|improve this answer


























                  2












                  2








                  2







                  There are almost no redeeming qualities in bubble sort, the nicest thing about it is its name. Donald Knuth has said that




                  the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems




                  And indeed, from Wikipedia about selection sort:




                  Among simple average-case Θ(n²) algorithms, selection sort almost always outperforms bubble sort and gnome sort.




                  There is no variation in selection sort - its running time does not depend on the ordering. For another good simple O(n²) algorithm that has variable running time, see insertion sort.






                  share|improve this answer













                  There are almost no redeeming qualities in bubble sort, the nicest thing about it is its name. Donald Knuth has said that




                  the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems




                  And indeed, from Wikipedia about selection sort:




                  Among simple average-case Θ(n²) algorithms, selection sort almost always outperforms bubble sort and gnome sort.




                  There is no variation in selection sort - its running time does not depend on the ordering. For another good simple O(n²) algorithm that has variable running time, see insertion sort.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 21:16









                  Antti HaapalaAntti Haapala

                  84.9k16161202




                  84.9k16161202






























                      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%2f53327710%2fcan-a-selection-sort-algorithm-terminate-from-its-loop-early-the-way-a-bubble-so%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

                      Florida Star v. B. J. F.

                      Error while running script in elastic search , gateway timeout

                      Adding quotations to stringified JSON object values