Thread: Need help with my Sorting code.

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    9

    Need help with my Sorting code.

    Code:
    /*
     |========================================|
     |===          Assignment 4: Team 5    ===|
     |=== Brandon                          ===|
     |===               John               ===|
     |===                           Adrian ===|
     |========================================|
     /*****************************SPECS*****************************\
     |**** Write a program that uses a menu system. The program ****|
     |**** will contain a character array and both a bubble ****|
     |**** bubble sort and binary search. The program will sort ****|
     |**** inputs and display them at the users request. ****|
     \***************************************************************/
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    
    #define pause system("pause")
    #define cls system("cls")
    #define SIZE 500
    #define flush fflush(stdin)
    
    
    //Prototype Functions:
    void displayArray(char c[], int counter);
    void displayEnd();
    void displayError();
    void displayIntro();
    void displayMenu();
    void displaySpecs();
    void getChar(char c[], int *counter);
    void getUserChoice(char *input);
    void orderZA(char array[]);
    void orderAZ(char array[]);
    void doTheSwitch(char array[], char i, char *switchMade);
    
    
    main(){
    char characters[SIZE]={0}, input=' ';
    int counter = 0, i;
    displayIntro();
    displaySpecs();
        do{
            displayMenu();
            getUserChoice(&input);
            switch(input){
                case 'A': //Add a character to the array
                    getChar(characters, &counter);
                    break;
                case 'B':
                orderAZ(characters);
                     break;
    
                case 'C':
                orderZA(characters);               
                     
                     break;
                      /* case 'D': //Search for a character
                     
                     break;*/
                case 'E': //Display the array
                    displayArray(characters, counter);
                    break;
                case 'Q': //Quit
                    input='Q';
                    break;
                default:
                    displayError();
                    break;
            } //End of Switch
            cls;
        }while(input!='Q'); //End of do
        displayEnd();
        pause;
    }//End of main
    
    
    void displayArray(char c[], int counter){
    int i=0;
    cls;
    printf("|****************************************|\n");
    printf("|****\t       |Array Inputs|\t     ****|\n");
    printf("|****************************************|\n\n");
    if(counter==0)
    printf("****Please Input Characters To Store\n");
    else
    for(i=0; i<counter; i++)
    printf("===========++\t    %i. %2c     ++===========\n", i+1, c[i]);
    printf("\n");
    pause;
    }//End of displayOutput
    
    
    void displayEnd(){
    printf("|****************************************|\n");
    printf("|****\t    Thank You for Using\t     ****|\n");
    printf("|****\t     Our Array Program\t     ****|\n");
    printf("|****************************************|\n\n");
    }//End of displayEnd Function
    
    
    void displayError(){
    cls;
    printf("|*****************|\n");
    printf("|*****ERROR*******|\n");
    printf("|*****************|\n\n");
    printf("======Please enter a vald Menu Input=====\n\n");
    pause;
    }//End of error Function
    
    
    void displayIntro(){
    printf("|========================================|\n");
    printf("|===\t      EXAM 4: Team 5\t      ===|\n");
    printf("|===\tBrandon\t\t\t      ===|\n");
    printf("|===\t\t   John\t\t      ===|\n");
    printf("|===\t\t\t  Adrian      ===|\n");
    printf("|========================================|\n\n");
    }//End of displayIntro Function
    
    
    void displayMenu(){
    printf("|****************************************|\n");
    printf("|****\t       +++|MENU|+++\t     ****|\n");
    printf("|****************************************|\n");
    printf("|\t\t\t\t\t |\n");
    printf("|  A. Add A Character To The Array\t |\n");
    printf("|  B. Put Array In Order From A-Z\t |\n");
    printf("|  C. Put Array In Order From Z-A\t |\n");
    printf("|  D. Search for a character\t\t |\n");
    printf("|  E. Display The Array\t\t\t |\n");
    printf("|  Q. Quit\t\t\t\t |\n");
    printf("|\t\t\t\t\t |\n");
    printf("|****************************************|\n\n");
    }//End of displayIntro Function
    
    
    void displaySpecs(){
    char ans=' ';
    printf("Would you like to view the specs?(Y or N) ");
    scanf("%c", &ans);
    ans=toupper(ans);
    if(ans=='Y'){
    cls;
    printf("|********************************************|\n");
    printf("|******\t         PROGRAM SPECS         ******|\n");
    printf("/********************************************\n");
    printf("|**    Write a program that uses a menu    **|\n");
    printf("|**    system. The program will contain    **|\n");
    printf("|**    a character array and both a        **|\n");
    printf("|**    bubble sort and binary search.      **|\n");
    printf("|**    The program will sort inputs and    **|\n");
    printf("|**    display them at the users request   **|\n");
    printf(" ********************************************/\n\n");
    printf("To view the menu...\n");
    pause;
    flush;
    cls;
    }//End if
    else
    flush;
        cls;
    }//End of displaySpecs Function
    
    
    void getChar(char c[], int *counter){
    cls;
    printf("|****************************************|\n");
    printf("|****\t    Type A Character(s)\t     ****|\n");
    printf("|****************************************|\n\n");
    printf("====>: ");
    scanf("%c", &c[*counter]);
    flush;
    (*counter)++;
    
    }//End of getSentence
    
    
    void getUserChoice(char *input){
    printf("Enter Your Choice: ");
    scanf("%c", input);
    flush;
        
    *input=toupper(*input);
    }//End getUserChoice Function
    
    
    void orderAZ(char array[]){
    int i, bottom;
    char switchMade;
    bottom = 0;
    do { 
         switchMade = 'N';
         for(i=0; i < bottom; i++) { 
            if(array[i] > array[i+1]) 
               doTheSwitch(array, i, &switchMade);
         } // end for
         bottom--;
       }while(switchMade == 'Y');
    return;
    } // end of orderAZ Function
    
    
    void orderZA(char array[]){
    int i, bottom;
    char switchMade;
    bottom = SIZE - 1;
    do { 
         switchMade = 'N';
         for(i=0; i < bottom; i++) { 
            if(array[i] < array[i+1]) 
               doTheSwitch(array, i, &switchMade);
         } // end for
         bottom--;
       }while(switchMade == 'Y');
    return;
    } // of orderZA
    void doTheSwitch(char array[], char i, char *switchMade) {
        int temp;       
        temp = array[i];
        array[i] = array[i+1]; 
        array[i+1]= temp; 
        *switchMade = 'Y'; 
    } // end function doTheSwitch
    Last edited by John120788; 07-11-2013 at 07:44 PM.

  2. #2
    Registered User
    Join Date
    Jun 2013
    Posts
    9
    Im currently having problems with my Function Void orderAZ. I want it to sort the letters in alphabatecial order but it doesnt seem to work. My other function Void orderZA works. What am I possibly doing wrong.

    Code:
    void orderAZ(chararray[]){
    int i, bottom; char switchMade; bottom = 0; do { switchMade = 'N'; for(i=0; i < bottom; i++) { if(array[i] > array[i+1]) doTheSwitch(array, i, &switchMade); } // end for bottom--; }while(switchMade == 'Y'); return; } // end of orderAZ Function

  3. #3
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    First of all, main() always returns int. You haven't specified a return type so technically the above code shouldn't compile.

    Second of all, your indentation is very inconsistent, and it makes your code harder to read, which means it makes it harder for us to help you.

    Third of all, this is an atrocity:

    Code:
    #define pause system("pause")
    #define cls system("cls")
    #define flush fflush(stdin)
    Using the preprocessor like this is a horrible idea, for a million different reasons. Not only that but the system() command is unsafe and not really portable and fflush() is only to be used on output streams, using it on stdin will give you undefined behaviour.

    It seems like you are supposed to implement the binary search algorithm yourself. A word of warning, although it is simple on paper it is known to be notoriously difficult to get right in code, and to be frank it doesn't make for a good exercise in my opinion.

    Finally, you just posted a bunch of code, without actually asking a question or specifying what seems to be wrong. If you don't put in the effort when asking the question, don't expect anyone to put in any effort when answering.

    Edit:

    Im currently having problems with my Function Void orderAZ. I want it to sort the letters in alphabatecial order but it doesnt seem to work. My other function Void orderZA works. What am I possibly doing wrong.
    Why are you decrementing 'bottom' in the do-while? After the first iteration you are comparing i to -1 and the inner for-loop terminates right away.

    Edit 2:

    In fact the for loop will run indefinitely on the first iteration, since i and 'bottom' is both 0 and i < bottom will thus never be true since you're incrementing i in the loop. You really need to fix your loops.
    Last edited by Neo1; 07-11-2013 at 07:37 PM.
    How I need a drink, alcoholic in nature, after the heavy lectures involving quantum mechanics.

  4. #4
    Registered User
    Join Date
    Jun 2013
    Posts
    9
    It all compiles. Im currently in an intro to programming class so I know it doesn't look perfect sorry. As for indentation, my professor likes it like this for some reason. He said its his preference. My question which I tried stating in comment two is that I just need my bubble sort in my function "Void orderAZ" to work. It not putting it in alphabetical order. I would like to know what Im doing wrong for that line of code which I copied an pasted in comment two. For the binary search, we have one guy working on that as we speak, thats why its not in our program yet. How do I get my bubble sort to work for my function Void orderAZ?????
    Any help would be greatly appreciated.

  5. #5
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    Quote Originally Posted by John120788 View Post
    It all compiles. Im currently in an intro to programming class so I know it doesn't look perfect sorry. As for indentation, my professor likes it like this for some reason. He said its his preference. My question which I tried stating in comment two is that I just need my bubble sort in my function "Void orderAZ" to work. It not putting it in alphabetical order. I would like to know what Im doing wrong for that line of code which I copied an pasted in comment two. For the binary search, we have one guy working on that as we speak, thats why its not in our program yet. How do I get my bubble sort to work for my function Void orderAZ?????
    Any help would be greatly appreciated.
    Code:
    void orderAZ(chararray[]){
    int i, bottom;
    char switchMade;
    bottom = 0;
    do { 
         switchMade = 'N';
         for(i=0; i < bottom; i++) { 
            if(array[i] > array[i+1]) 
               doTheSwitch(array, i, &switchMade);
         } // end for
         bottom--;
       }while(switchMade == 'Y');
    return;
    } // end of orderAZ Function
    The problem is that your for-loop isn't doing what you think it is doing. Initially 'bottom' is 0 and i is zero, and since i is only incremented, the loop will never terminate. This means i just keeps getting bigger and bigger ultimately resulting in a segfault because you have exceeded the bounds of the array. Look real hard at that for-loop, that is where the problem is.
    How I need a drink, alcoholic in nature, after the heavy lectures involving quantum mechanics.

  6. #6
    Registered User
    Join Date
    Jun 2013
    Posts
    9
    Ok so I changed bottom to bottom gets SIZE - 1; But the letters dont show up at all. I believe its since the array is declared to be 500 then when I use this code it pushes the letters to the last elements in the array. I think thats what going on. Causing it to not show the letters. How do I get the letters to be in the first elements of the array instead of the last ones?? But thanks for pointing out the bottom being initialized to zero.

    Code:
      void orderAZ(chararray[]){    
       int i, bottom;
       char switchMade;
       bottom = SIZE - 1;
       do { 
        switchMade = 'N';
        for(i=0; i < bottom; i++) { 
           if(array[i] > array[i+1]) 
              doTheSwitch(array, i, &switchMade);
        } // end for
        bottom--;
      }while(switchMade == 'Y');
    return;
    } // end of orderAZ Function
    
    Last edited by John120788; 07-11-2013 at 08:04 PM.

  7. #7
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Add a check for zero, and never do a swap if the later element is zero.

  8. #8
    Registered User HelpfulPerson's Avatar
    Join Date
    Jun 2013
    Location
    Over the rainbow
    Posts
    288
    This would be a lot easier if you could use qsort() for this. You would still have to write your own comparator functions, but it would save from a lot of unneeded variables and code.

  9. #9
    Registered User
    Join Date
    May 2012
    Posts
    505
    Quote Originally Posted by HelpfulPerson View Post
    This would be a lot easier if you could use qsort() for this. You would still have to write your own comparator functions, but it would save from a lot of unneeded variables and code.
    The thing to do is to write the program using qsort, then write bubblesort() to take exactly the same parameters and have exactly the same output (assuming equal elements are identical).
    You can knock up a little program to generate millions of random lists to really test that your bubblesort works. So you know that any problems must be elsewhere.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help sorting structure by male/female and zip code
    By usmcrewcheif in forum C Programming
    Replies: 3
    Last Post: 05-18-2010, 01:16 AM
  2. Zip Code Sorting
    By Shamino in forum C++ Programming
    Replies: 14
    Last Post: 10-26-2009, 04:20 PM
  3. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  4. Complete beginner needs help customising sorting code
    By Ian SH in forum C++ Programming
    Replies: 4
    Last Post: 11-03-2007, 07:09 PM
  5. Sorting Linked Lists (code not concept)
    By Newbie Magic in forum C++ Programming
    Replies: 2
    Last Post: 05-11-2004, 08:57 AM