Thread: Sorting an array

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    11

    Question Sorting an array

    Hi, I'm new in this forum and also new at programming

    I'm taking a C course at college but our lecturer is quite lazy, so we need to investigate most of the stuff. Currently, I'm stuck working with an array exercise, after headdesking for a while I managed to declare and initialize one, but I've problems sorting its elements.

    Exercise: creating an array of five elements as doubles, asking the user to enter values and print the sorted array.

    This is what I wrote so far:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    
    double value[5]={'\0','\0','\0','\0','\0'};
    
    /* User interaction module */
    system("clear");
    
    puts("Please enter five values:");
    	scanf("%lf", &value[0]);
    	scanf("%lf", &value[1]);
    	scanf("%lf", &value[2]);
    	scanf("%lf", &value[3]);
    	scanf("%lf", &value[4]);
    
    /* Printing the array */
    printf("%lf, %lf, %lf, %lf, %lf \n", value[0], value[1], value[2], value[3],value[4]);
    
    return(0);
    }
    I can ask for 5 numbers stored as doubles (as asked in the problem) but I don't know how to sort the numbers. I've tried everything but without success, so I'm asking for help here

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Have you tried searching for "sorting algorithm" on the internet? Did your textbook try to teach you a sort you could use?

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    11
    I searched and I found a function named qsort which can sort the values in the array but I don't really understand how it works the examples I found run, but I still don't know how to adapt them to my needs.

    Our textbook is very basic, so it doesn't have much info :/

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Using qsort would be a bad idea since your teacher probably wants to see you write the sort yourself. I'm actually kind of surprised that qsort is either one of the first things you found, or the thing you decided to go with, because sorting is basically the most commonly solved problem, here, and on the rest of the Web. Anything linked here will teach you how to write a sort. Try bubble sort.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    11
    Finished coding, and it works thank you for your help!
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    
    double value[5]={'\0','\0','\0','\0','\0'};
    double keeper;
    int num;
    
    /* User interaction module */
    system("clear");
    
    puts("Please enter five values:");
    	scanf("%lf", &value[0]);
    	scanf("%lf", &value[1]);
    	scanf("%lf", &value[2]);
    	scanf("%lf", &value[3]);
    	scanf("%lf", &value[4]);
    
    for(num=1; num<=10; num++){
    /* 0 - 1 */
    if (value[0]<value[1]){
    keeper=value[1];
    value[1]=value[0];
    value[0]=keeper;
    keeper='\0';
    }
    
    /* 1 - 2 ] */
    if (value[1]<value[2]){
    keeper=value[2];
    value[2]=value[1];
    value[1]=keeper;
    keeper='\0';
    }
    
    /* 2 - 3  */
    if (value[2]<value[3]){
    keeper=value[3];
    value[3]=value[2];
    value[2]=keeper;
    keeper='\0';
    }
    
    /* 3 - 4 */
    if (value[3]<value[4]){
    keeper=value[4];
    value[4]=value[3];
    value[3]=keeper;
    keeper='\0';
    }
    }
    /* Printing the array */
    printf("%lf, %lf, %lf, %lf, %lf \n", value[0], value[1], value[2], value[3],value[4]);
    
    return(0);
    }
    It's totally unoptimized but, I'll do that tomorrow, for now going to sleep with something done already hehe, thanks!

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Your code is assigning a character ('\0') to a double. Whist the type promotion mechanism will allow this to work, really it is not the right thing to do, and at the very least confuses the reader.
    To assign a zero value to a double just assign 0.0, or simply 0.
    Also note that you don't need to set keeper back to zero after you've used it for a swap. You can happily just leave it with whatever value it had until the next time it is used for a swap, at which point it is ovewritten.

    Yes that is a bubble sort, but yes it is inefficient in almost every way possible .
    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"

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    11
    Oh you're right :O I just deleted the keeper reset lines and initialized the array with zeros instead of '\0' 's it's my first time working a non-char array so I need to work on it.

  8. #8
    Registered User
    Join Date
    Jan 2011
    Posts
    41
    Inside your loop you basically do the same thing 4 times just with different numbers, you should write a swap function to get rid of all the redundant code.

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    It would also be cool if there was a loop inside the other loop that repeated those four calls to your new swap function, just with different numbers. This would be really helpful if you wanted to, say, change your code to sort a list of 10, or 100 numbers (Imagine the work involved for such a change in your current code).

  10. #10
    Registered User
    Join Date
    Jun 2011
    Posts
    11
    Okay, I changed some lines with loops and got this

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    
    double value[5]={0,0,0,0,0};
    double keeper;
    int i,j,k;
    
    /* User interaction module */
    	system("clear");
    	puts("Please enter five values:");
    
    /* Storing every value in the array */
    	for(j=0;j<=4;j++)
    		{
    		scanf("%lf", &value[j]);
    		 }
    
    	for(i=1; i<=10; i++) /* Swaps through the re-arranged array */
    		{ 
    		for(k=0; k<=4; k++) /* Looping the switch for every pair */
    			{ 
    			if (value[k]<value[k+1]) /* Switching */
    		 		{
    				keeper=value[k+1];
    				value[k+1]=value[k];
    				value[k]=keeper;
    				}
    			}
    		}
    
    /* Printing the array */
    	for(j=0;j<=4;j++)
    		{
    		printf("%lf ", value[j]);
    		}
    	
    putchar('\n');
    return(0);
    }
    It's indeed much better now and it works.

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by dxgalaxy View Post
    It's indeed much better now and it works.
    Are you sure about that?
    You are allowing k to go up to 4, and then access value[k+1] i.e. value[5]. That's out of bounds for an array with elements 0 to 4. You probably happen to be lucky that whatever value is in the ouf of bounds memory location, happens to no smaller than the other values.
    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"

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This is a substitution sort - very similar to a bubble sort. I suggest you study it, and memorize it for small sorting jobs.

    Code:
    #define SizeOfTheArray 10
    
    int Array[SizeOfTheArray];
    int i, j, temp;
    
    //enter your numbers into the array, here.
    
    //substitution sort
    
    for(i = 0; i < sizeOfTheArray-1; i++) {    //the minus 1 is not essential, but optimal
       for(j = i+1; j < sizeOfTheArray; j++) {   //j starts with i+1, not zero 
          if(Array[i] > Array[j])  {  //replace > with < for descending sort
             temp = Array[i];
             Array[i] = Array[j];
             Array[j] = temp;
          }
       }
    }
    I believe that is the most intuitive and simplest sort around. (Gnome sort is simpler but not as intuitive, imo).

    If you have less than 100 numbers to sort, it's fast. It's very slow on large amounts of numbers however, being just a step up from a bubble sort.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Adding nodes to an array at the top & array sorting
    By Wolf` in forum C++ Programming
    Replies: 1
    Last Post: 06-25-2010, 12:48 PM
  2. Replies: 9
    Last Post: 04-07-2010, 10:03 PM
  3. Array Sorting ???
    By Takis_ in forum C++ Programming
    Replies: 7
    Last Post: 04-04-2008, 10:38 AM
  4. 2D array sorting from min. to max.
    By khaled_helmy in forum C Programming
    Replies: 1
    Last Post: 10-14-2004, 02:17 PM

Tags for this Thread