Selection Sort - strange output

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • June Ye
    New Member
    • Feb 2011
    • 14

    Selection Sort - strange output

    Hi,

    I was writing insertion sort in c++.
    However the output is very strange.

    input:79261458

    output: 11111458

    Following is the code.

    Could someone help to point out the error?

    Thank you!


    Code:
    #include <iostream>
    
    using namespace std;
    
    void insertionSort(int* input, int size)
    {
    
          for(int j = 1; j <size; j++){
            int value = *(input+j);
            for(int k = 0; k < j; k++){
               if(*(input+k) > value){
                  for(int l = j; l > k; l--){
                     *(input+l) = *(input+l-l);
                  }
                  *(input+k) = value;
               }
            }
          }
    }
    
    int main()
    {
        int input[] = {7,9,2,6,1,4,5,8};
    
        insertionSort(input, 8);
        for(int i = 0; i <8; i++)
          cout<< *(input+i);
       
        cout << endl;
        system("pause");
        
        return 0;
    
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I suggest you step through you code with a debugger.

    Also l is an extremely bad name for a single letter variable because it is too easy to confuse with 1, for example see *(input+l-l)

    EDIT: Looking at the how what I just wrote appears I believe you have a error because of this issue. I think you have *(input+l-l) when you mean *(input+l-1)

    Comment

    • June Ye
      New Member
      • Feb 2011
      • 14

      #3
      Thanks! Here is the correct one.

      Code:
      #include <iostream>
      #include <math.h>
      
      using namespace std;
      
      void insertionSort(int* input, int size)
      {
            for(int i = 0; i <size; i++){
              int value = *(input+i);
              int j = i;
              while (j>0 && (*(input+i) > *(input+j-1)) ) j--;
      
              for(int k = i; k > j; k--){
                 *(input+k) = *(input+k-1);
              }
             *(input+j) = value;
            }
      }
      
      int main()
      {
          int input[] = {7,9,2,6,1,4,5,8};
      
          insertionSort(input, 8);
          for(int i = 0; i <8; i++)
            cout<< *(input+i);
         
          cout << endl;
          system("pause");
          
          return 0;  
      }

      Comment

      Working...