Thread: Sorting problem?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Ugly C Lover audinue's Avatar
    Join Date
    Jun 2008
    Location
    Indonesia
    Posts
    489

    Question Sorting problem?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
      int id;
      const char *data;
    } Test;
    
    int main() {
      Test **array = malloc(3 * sizeof(Test *));
    
      (*(array)) = malloc(sizeof(Test));
      (*(array))->id = 3;
      (*(array))->data = "3";
    
      (*(array + 1)) = malloc(sizeof(Test));
      (*(array + 1))->id = 2;
      (*(array + 1))->data = "2";
      
      (*(array + 2)) = malloc(sizeof(Test));
      (*(array + 2))->id = 1;
      (*(array + 2))->data = "1";
    
      int i;
      for(i=0; i<3; i++) {
        printf("%s ", (*(array + i))->data);
      }
      
      for(i=1; i<3; i++) {
        int j;
        for(j=i; j>-1; j--) {
          if(((*(array + i))->id) < ((*(array + j))->id)) {
            Test *tmp = *(array + i);
            *(array + i) = *(array + j);
            *(array + j) = tmp;
          }
        }
      }
    
      printf("\n");
    
      for(i=0; i<3; i++) {
        printf("%s ", (*(array + i))->data);
      }
    
      return 0;
    }
    Can anyone guess?
    Is there something wrong with its algorithm or code?

    The output should be: 1 2 3
    But it is: 2 1 3

    ?
    Last edited by audinue; 01-05-2009 at 05:01 PM.
    Just GET it OFF out my mind!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting (asymptotic) complexity problem
    By Petike in forum C++ Programming
    Replies: 8
    Last Post: 01-20-2009, 07:15 AM
  2. Array Sorting problem
    By ___________ in forum C++ Programming
    Replies: 4
    Last Post: 07-22-2008, 12:17 AM
  3. What is problem about the sorting?
    By Mathsniper in forum C Programming
    Replies: 2
    Last Post: 04-17-2005, 07:00 AM
  4. Sorting text file problem...
    By John-m in forum C Programming
    Replies: 3
    Last Post: 10-01-2002, 04:51 PM
  5. Sorting array output problem
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 02-19-2002, 01:44 PM