sorting an array of numbers in C

This is a discussion on sorting an array of numbers in C within the C Programming forums, part of the General Programming Boards category; Say I have an array (num[3]) that holds 3 numbers. How could I sort those numbers in order from highest ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    1

    sorting an array of numbers in C

    Say I have an array (num[3]) that holds 3 numbers. How could I sort those numbers in order from highest to lowest and store them in individual integer variables (highest, middle, lowest) using C? For example:
    Code:
    int num1 = 5;
    int num2 = 4;
    int num3 = 9;
    int num[3];
    int highest, middle, lowest;
    
    num[1] = num1;
    num[2] = num2;
    num[3] = num3;
    And sort it so that highest = 9, middle = 5, and lowest = 4.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,786
    You would do some comparisons. Try and work it out on paper, or perhaps by using some pens of different lengths to help you see the solution.
    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

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,313
    It only takes 3 comparisons and exchanges, and is called a "three input sorting network".
    Got it yet?
    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"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Writing unique numbers to an array
    By yardy in forum C Programming
    Replies: 6
    Last Post: 12-27-2006, 08:15 PM
  2. HELP:::MIX numbers in array
    By ypramesh in forum C Programming
    Replies: 9
    Last Post: 03-30-2006, 06:47 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 12:01 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21