Thread: Need help sorting 2 arrays.

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    15

    Need help sorting 2 arrays.

    Hello everyone.

    I'm trying to write a program where a user will enter a set of x,y coordinates and the program will sort them based on their distance from the origin using sqrt (x*x + y*y). The x and y coordinates each go into their own array, but are supposed to be sorted in one function.

    This is what i have so far.


    Code:
    #include <stdio.h>
    #include <math.h>
    
    #define MAX_LIST_SIZE 10
    
    
    float calc_z (int x, int y);
    void sort_xy (int x[], int y[]); 
     
    int i,j,hold, choice, coordNumber;
      int x[MAX_LIST_SIZE], y[MAX_LIST_SIZE];
    
    
    void main () {
     
    
      while (1) {
        printf ("Enter (1) to run (2) to quit: ");
        scanf ("%d", &choice);
        if (choice == 2) return;
        else {
          printf("How many coordinates do you want to enter in: ");
          scanf ("%d", &coordNumber);
    	
    	
    	
    	  for (i = 0; i < coordNumber; i++) {
    	printf ("enter x,y: ");
    	scanf ("%d,%d", &x[i], &y[i]);
    	  }
      
    	  
    void sort_xy (int x[], int y[]);
    	  
    	  
    	  for (i = 0; i < coordNumber; i++) {
    		printf("%d %d\n", x[i], y[i]);}
    	  }
          
        }
      }
    
    
    
    
    
    void sort_xy (int x[], int y[]){
    
    	for (j=1; j<coordNumber; j++){
    		for (i=0; i < coordNumber-1; i++){         
                                                         /*  VV Problem here probably  VV*/
    			if (float sqrt(x[i]*x[i]+y[i]*y[i]) >  float sqrt(x[i+1]*x[i+1]+y[i+1]*y[i+1])) {
    				hold= x[i+1];
    				x[i + 1]=x[i];
    				x[i] = hold;
    			}}}}
    When I try to build this I get the following errors:

    error C2061: syntax error : identifier 'x'
    : error C2059: syntax error : '>'
    error C2143: syntax error : missing ';' before '{'


    I have tried using another function to figure out the distance, but I couldn't figure out how to incorporate it into the sorting one.
    If someone could point this noob in the right direction it would be greatly appreciated.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Why do you have the words "float" in your sort_xy function?

  3. #3
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    "(float sqrt(x[i]*x[i]+y[i]*y[i]) > float sqrt(x[i+1]*x[i+1]+y[i+1]*y[i+1]))"

    ???

    try (sqrt((float)(x[i]*x[i]+y[i]*y[i])) > sqrt((float)(x[i+1]*x[i+1]+y[i+1]*y[i+1])))

  4. #4
    Registered User
    Join Date
    Oct 2009
    Posts
    15
    Quote Originally Posted by Epy View Post
    "(float sqrt(x[i]*x[i]+y[i]*y[i]) > float sqrt(x[i+1]*x[i+1]+y[i+1]*y[i+1]))"

    ???

    try (sqrt((float)(x[i]*x[i]+y[i]*y[i])) > sqrt((float)(x[i+1]*x[i+1]+y[i+1]*y[i+1])))

    That got rid of the errors. It's still not sorting though. Ill have to mess with it.

    For the other question. I had the float in there because without it it gives me a
    error C2668: 'sqrt' : ambiguous call to overloaded function.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You don't need the sqrts in there anyway!
    sqrt(a) is greater than sqrt(b) if and only if a is greater than b.
    This exact thing is a very common optimsation.

    Do you think that perhaps you need to swap the y values along with the swapping of the x values? Otherwise they get out of sync and all muddled up.

    learn to use local variables. Having them all as a global is very bad!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    void sort_xy (int x[], int y[])  {
    
      for (i = 0; i < coordNumber-1; i++)  {
        for (j = i+1; ji< coordNumber; j++)  {         
                /*  VV Problem here probably  VV*/
          if (float sqrt(x[i]*x[i]+y[i]*y[i]) >  float sqrt(x[j]*x[j]+y[j]*y[j]))  {
    	hold= x[j];
    	x[j]=x[i];
    	x[i] = hold;
          }
        }
      }
    }
    If you want to also sort the y portion, you need to repeat the section in blue, but swap the y values, instead.
    Last edited by Adak; 10-10-2009 at 01:10 AM.

  7. #7
    Registered User
    Join Date
    Oct 2009
    Posts
    15
    So I wrote the function out like this:

    Code:
    void sort_xy (int x[], int y[] )  {
    int hold1, hold2,j;
      for (i = 0; i < coordNumber -1 ; i++)  {
        for (j = i + 1 ; j < coordNumber; j++)  {         
               
          if (sqrt((float)(x[i]*x[i]+y[i]*y[i])) > sqrt((float)(x[j]*x[j]+y[j]*y[j])))  {
    	hold1= x[j];                         
    	x[j]=x[i];
    	x[i] = hold1;
    	hold2= y[j];                         
    	y[j]=y[i];
    	y[i] = hold2;
         }
        }
      }}
    It still doesn't sort, however.

    I also tried writing a separate function to determine the square root.
    Code:
    float calc_z (int x, int y) {
    	float distance1;
    	float distance2;
    	distance1 = (x*x)+(y*y);
    	distance2 =  sqrt(distance1);
    	return distance2;}
    But I can't figure out how to make it work with the other function.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Hey! Don't be talking bad about my favorite bubble sorter, now!

    It's sorting just fine, but you're not getting what you want, because you're not using sqrt() correctly.

    It's not enough to just say: sqrt(variable). You have to ASSIGN the result returned by sqrt(), into a variable.

    like so:

    Code:
    #include <stdio.h>
    #include <math.h>
    
    
    int main(void) {
    
       double num = 5.0;
       double result = 0.0;
    
       result = sqrt(num);
       printf("The square root of %lf is %lf", num, result);
    
       printf("\n\n\t\t\t     press enter when ready");
       num= getchar();
       return 0;
    }
    So, the sorter is fine, but you haven't changed any values in X[], since the results returned by sqrt(), were not saved anywhere.
    Rumor has it they went to byte heaven.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Posto2012
    For the other question. I had the float in there because without it it gives me a
    error C2668: 'sqrt' : ambiguous call to overloaded function.
    You might want to compile your C programs as C instead of C++.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Oct 2009
    Posts
    15
    So, when I have the square root of the coordinates, how would I implement it in my function to sort the two arrays?

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Posto2012 View Post
    So, when I have the square root of the coordinates, how would I implement it in my function to sort the two arrays?
    What do you want to sort by? Pick a key!

    We could sort by the values in x[i], or by the values in y[i], or by things like x[i]+y[i], or by their distances?

    Any key will be unlikely to match the sort order of any other key.

    Choose your key, then it's ez-squeezy.

  12. #12
    Registered User
    Join Date
    Oct 2009
    Posts
    15
    I need to sort the two arrays of x,y coordinates by their distance from the origin.
    The user selects the coordinates and they go into two arrays, one for x and one for y.
    So, i have to get the distance, and somehow resort the x and y pairs at the same time.

  13. #13
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Oh dear, you didn't listen I've already explained that sqrt(a) is greater than sqrt(b) if and only if a is greater than b. Let me put it another way however...
    Would you do this:
    Code:
    if (a*2 > b * 2)
    when you could just do this:
    Code:
    if (a > b)
    That's just like what you're doing by keeping the sqrts.

    It makes no difference if you're asked to compare the distances or squared-distances, they are both going to give the same result.

    Trust me, plenty of your classmates with the same assignment will leave the sqrts out, and they will likely get a better mark for having simpler (and much faster) code.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  14. #14
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Posto2012 View Post
    Code:
    void sort_xy (int x[], int y[] )  {
    int hold1, hold2,j;
      for (i = 0; i < coordNumber -1 ; i++)  {
        for (j = i + 1 ; j < coordNumber; j++)  {         
               
          if (sqrt((float)(x[i]*x[i]+y[i]*y[i])) > sqrt((float)(x[j]*x[j]+y[j]*y[j])))  {
    	hold1= x[j];                         
    	x[j]=x[i];
    	x[i] = hold1;
    	hold2= y[j];                         
    	y[j]=y[i];
    	y[i] = hold2;
         }
        }
      }}
    This code, apart from being badly formatted and containing some unnecessary sqrts, is actually completely correct, and will sort the array exactly as it should.

    Adak, I thought you had seen me say this before, but that is not Bubble Sort! Bubble Sort is a stable sorting algorithm that only swaps adjacent items. Here i and j often differ by more than 1 so it swaps non-adjacent items and is not a stable sort, and not Bubble Sort. In fact if you see it animated you'll see a distinct lack of bubbling going on!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by iMalc View Post
    This code, apart from being badly formatted and containing some unnecessary sqrts, is actually completely correct, and will sort the array exactly as it should.

    Adak, I thought you had seen me say this before, but that is not Bubble Sort! Bubble Sort is a stable sorting algorithm that only swaps adjacent items. Here i and j often differ by more than 1 so it swaps non-adjacent items and is not a stable sort, and not Bubble Sort. In fact if you see it animated you'll see a distinct lack of bubbling going on!
    My bubble sort won't "bubble"? << eek! >>

    I know it's not THE Bubble Sort, but that's the best name I've found for it. Maybe I should call it "bubble sorter", because it's "sorter" like bubble sort. < LOL >

    Bubble sort is a bit faster than this one, but also a few more lines of code. Maybe I could call it "Ezsort". Sounds funny, but it fits it.

    Would x[i] + y[i] comparing with x[j] + y[j] be good to sort by?

    Maybe he needs to calculate and save the distances, and doesn't realize that you don't want to do that, in a sorting function - it makes for a lot of unnecessary computer work.

    Posto, iMalc has given you some great advice here. You do NOT want to work with the sqrt() during the sorting code - it's horrid to have it here, and unneeded.

    If you need to use sqrt(), then do it ONCE for each value, in another function, and save it.
    (I'd use another array).

    During sorting, sqrt() will have to be calculated many times over, for each value in the arrays. You DON'T want that!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 06-11-2009, 11:27 AM
  2. Sorting Arrays
    By DaniiChris in forum C Programming
    Replies: 11
    Last Post: 08-03-2008, 08:23 PM
  3. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  4. Replies: 2
    Last Post: 02-23-2004, 06:34 AM
  5. sorting arrays
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 10-13-2001, 05:39 PM