Home Forums C Programming Quick Sort for a Struct

Viewing 2 reply threads
  • Author
    Posts
    • #2168
      DixieFuqua
      Participant

      Hey i am new to c plus plus, and really need some help!
      Basically i have information, in a file, first name, second name and idnumber stored in a struct for a number of people as such:

      struct person {
      char idnumber [numbersize];
      char firstname [namesize];
      char secondname [namesize];

      };

      And i need to be able to sort it according to either first name, second name or in ascending idnumber using a quick sort. Is it possible to write a general function and use pointers to assign the relevant piece of information to sort by e.g first name etc?. Then, is it possible to call the function and print the sorted list?

      If someone could show me some helpful code or some hints it would be greatly appreciated.
      Thanks.

    • #3498
      GWILouisaxwzkla
      Participant

      The structs will form a linked list , correct? The sorting key will be variable amongst the struct field members ( the user will chose a struct member to sort the data on ) ?? Is the list to be “disconnected” for sorting ( structs will be moved and the list reconnected ) or is data to be shifted ( probably easier )…

    • #3499
      GWILouisaxwzkla
      Participant

      Heres a way to do this with a doubly linked list with quicksort. This version of quicksort uses the last item in the
      list as a pivot element when partitioning.



      /****************************************************************
      * File Name : c:programstempCG.cpp
      * Date : January,6,2008
      * Comments : new project
      * Compiler/Assembler :
      * Modifications :
      *
      *
      *
      *
      *
      * Program Shell Generated At: 3:51:46 p.m.
      =-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


      #include < iostream >
      #include < fstream >
      //#include < string.h >
      //#include < conio.h >
      //#include < math.h >
      #include < iomanip >
      #include < ctype.h >

      using namespace std;

      //>>>>>>>>>>>>>>>>>>>>>>>> GLOBAL DATA <<<<<<<<<<<<<<<<<<<<<<<<<

      const int MAX_NAME = 50;
      const int MAX_FILE_NAME = 50;
      const char STOP_SYMBOL = '*';
      enum keys { firstName , lastName , idNumber };
      keys sortKey ;
      #define OUTPUT_SPACES 15
      //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<



      struct person
      {

      char firstName [ MAX_NAME ] ;
      char lastName [ MAX_NAME ] ;
      char idNumber [ MAX_NAME ] ;
      person * prior;
      person * next;
      };


      //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ FUNCTION PROTOTYPES @@@@@@@@@@@@@@@@@@@@@@@@@@

      bool readInputFile ( char * fileName , person *& frontList , person *& backList , int & itemsRead );
      void quickSort ( person ** front , person ** last , int numberItems );
      void swap ( person ** first , person ** last , person ** front , person ** back );
      void print ( person * list );
      void insertionSort ( person * list , int numberOfItems );
      void destroyList ( person * list );
      char * key ( person * node );

      //##################################################################################


      //main function ******************************

      int main ( )
      {

      person * front , * back;
      int items;

      sortKey = firstName;
      readInputFile ( "c:\programs\data.txt" , front , back , items );
      print ( front );
      quickSort ( & front , & back , items );
      cout << endl << endl;
      cout << "final ************************" << endl;
      print ( front );
      destroyList ( front );
      return 0 ;
      }


      /******************************* FUNCTION DEFINITION ******************************

      Name : readInputFile
      Parameters :

      fileName a(n) char * ,
      frontList a(n) person *& ( person *& ) ,
      backList a(n) person *& ( person *& ) ,
      itemsRead a(n) int &


      Returns: bool type
      Comments:



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      bool readInputFile ( char * fileName , person *& frontList , person *& backList , int & itemsRead )
      {


      fstream inputFile;
      person * temp;
      char ch;
      inputFile.open ( fileName ); //open input file
      if ( inputFile.fail () )
      {
      cout << "input file did not open! " << endl;
      return false;
      }
      temp = new person; //make new node in list
      if ( temp == 0 ) //if allocation error
      {
      cout << "allocation error! " << endl;
      return false;
      }
      itemsRead = 1; //start count at 1
      frontList = backList = temp; //set front and back pointers to new node
      temp -> prior = 0; //set new nodes prior to empty
      inputFile >> temp -> firstName; //get nodes data from file
      inputFile >> temp -> lastName;
      inputFile >> temp -> idNumber;
      ch = inputFile.peek(); //check for end of file character
      while ( isspace ( ch ) ) //skip white space
      {
      inputFile.get();
      ch = inputFile.peek();
      }
      while ( ch != STOP_SYMBOL ) //while not at end of file
      {
      temp -> next = new person; //make new item in the list
      if ( temp -> next == 0 ) //check allocation
      {
      cout << "allocation error! " << endl;
      destroyList ( frontList );
      return false;
      }
      temp -> next -> prior = temp; //set temp to point to new node
      temp -> next -> next = 0; //set next to empty
      temp = temp -> next;//move list pointer to next node
      backList = temp; //make new node the back of list
      inputFile >> temp -> firstName; //get data
      inputFile >> temp -> lastName;
      inputFile >> temp -> idNumber;
      ch = inputFile.peek(); //get white space
      while ( isspace ( ch ) )
      {
      inputFile.get();
      ch = inputFile.peek();
      }
      itemsRead ++;//count items read
      }

      return true;
      }
      /******************************* FUNCTION DEFINITION ******************************

      Name : quickSort
      Parameters :

      front a(n) person *& ( person *& ) ,
      last a(n) person *& ( person *& ) ,
      numberItems a(n) int ( int )


      Returns: Void type
      Comments:



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      void quickSort ( person ** low , person ** high , int numberItems )
      {


      person * savedLow = * low; //lowt
      person * savedHigh = * high;//hight
      person * tempLow , * tempHigh;
      person * pivot; //pivot for sorting

      if ( numberItems <= 1 ) //nothing to sort
      return;
      if ( numberItems == 2 ) //if 2 items then swap if needed
      {
      tempLow = * low;
      tempHigh = * high;
      if ( strcmp ( key ( tempLow ) , key ( tempHigh ) ) > 0 ) //swap items if out of order
      swap ( & tempLow , & tempHigh , & savedLow , & savedHigh );
      * low = tempLow; //reset low and high pointers
      * high = tempHigh;
      return ; //end function
      }



      pivot = savedHigh; //make the highest element in the array the pivot
      tempLow = savedLow; //start sorting at the lowest item in the list
      tempHigh = ( * savedHigh ).prior; //start sorting at the second to last item
      int lowCount = 1; //start counting at the first item for the low pointer
      int highCount = numberItems - 1; //start counting at the second to last item for high count

      do
      {

      //while items are less than the pivot move right
      while ( lowCount <= highCount && ( strcmp ( key ( tempLow ) , key ( pivot ) ) < 0 || strcmp ( key ( tempLow ) , key ( pivot ) ) == 0 ) )
      {


      tempLow = tempLow -> next;
      lowCount ++; //increase count of items behind pointer
      if ( ! tempLow )
      break;
      }
      //while items are greater than the pivot move right
      while ( lowCount <= highCount && ( strcmp ( key ( tempHigh ) , key ( pivot ) ) > 0 || strcmp ( key ( tempLow ) , key ( pivot ) ) == 0 ) )
      {


      tempHigh = tempHigh -> prior;
      highCount --; //decrease count of items before pointer
      if ( ! tempHigh )
      break;
      }

      if ( tempHigh ) //if top pointer has not crossed end of list , swap items
      swap ( & tempLow , & tempHigh , & savedLow , & savedHigh );

      } while ( lowCount <= highCount && tempHigh -> prior && tempLow -> next );

      if ( tempHigh ) //if high pointer has not passed the end to the list , exchange high and low pointers
      swap ( & tempLow , & tempHigh , & savedLow , & savedHigh );

      //put pivot in middle of large item and small item lists
      tempHigh = savedHigh;
      swap ( & tempLow , & tempHigh , & savedLow , & savedHigh );
      //sort list of small items
      quickSort ( & savedLow , & tempLow -> prior , lowCount - 1 );
      //sort list of large items
      quickSort ( & tempLow -> next , & savedHigh , numberItems - lowCount );
      //reset low and high pointers
      * low = savedLow;
      * high = savedHigh;

      return;
      }
      /******************************* FUNCTION DEFINITION ******************************

      Name : swap
      Parameters :

      first a(n) person *& ( person *& ) ,
      last a(n) person *& ( person *& )


      Returns: Void type
      Comments: first



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      void swap ( person ** left , person ** right , person ** front , person ** back )
      {


      if ( ! * left || !* right ) //if left or right pointer is null , stop
      return;
      if ( * left == * right )
      return;
      //reset the front and back pointers
      if ( ( * front ) == ( * left ) ) //if left == front
      {

      * front = * right; //right is new front after swap
      }
      else if ( ( * front ) == ( * right ) ) //if right == front
      {

      * front = * left; //left is new front after swap
      }
      if ( ( * back ) == ( * left ) ) //if left == back
      {

      * back = * right; //right is back after swap
      }
      else if ( ( * back ) == ( * right ) ) //if right is back
      {

      * back = * left; //left is back after swap
      }



      person * tempN , * tempP;

      tempN = ( * left ) -> next; //save left's next and prior node setting
      tempP = ( * left ) -> prior;

      //case 1: right node follows left in list
      if ( ( * right ) -> prior == * left )
      {
      ( * left ) -> prior = ( * right ); //right is left's new prior node
      ( * left ) -> next = ( * right ) -> next; //left's next node is right's old prior node
      if ( ( * left ) -> next ) //if left had a next node
      ( * left ) -> next -> prior = ( * right ); //set that nodes prior to right
      ( * right ) -> next = ( * left ); //right's next now is left
      ( * right ) -> prior = tempP; //right's new prior is left's old prior
      if ( tempP ) //if left's old prior is not null
      tempP -> next = ( * right ); //left's old prior's next is right
      }
      //case 2: left follows right in the list
      else if ( ( * left) -> prior == ( * right ) )
      {
      ( * left ) -> prior = ( * right ) -> prior; //left's prior is now right's prior
      ( * left ) -> next = ( * right ); //left's next is now right
      if ( ( * right ) -> prior ) //if right's prior is not null
      ( * right ) -> prior -> next = ( * left ); //set its next to left
      ( * right ) -> prior = ( * left ); //right comes after left node now
      ( * right ) -> next = tempN; //right's next is left's old next
      if ( tempN ) //if left's old next is non-null
      tempN -> prior = ( * right ); //set its prior to right
      }
      //case 3: the two nodes are seperated by other nodes
      else
      {
      ( * left ) -> prior = ( * right ) -> prior; //left's prior equal's right's
      ( * left ) -> next = ( * right ) -> next; //left's next equal's right's

      if ( ( * right ) -> next ) //if right's next is non-null
      ( * right ) -> next -> prior = ( * left ); //set it's prior to left
      if ( ( * right ) -> prior )//if right's prior is non-null
      ( * right ) -> prior -> next = ( * left ); //it's next now equals left
      ( * right ) -> prior = tempP; //right's prior now == left's
      ( * right ) -> next = tempN; //right's next now == left's
      if ( tempP ) //if left's prior was non-null
      tempP -> next = ( * right ); //set its next to right
      if ( tempN ) //if left's next was non-null
      tempN -> prior = ( * right );//set its prior to right
      }


      person * temp = ( * left ); //swap left and right pointers to save
      person * temp2 = ( * right );//position of pointers in the list
      ( * left ) = temp2;
      ( * right ) = temp;

      return;
      }
      /******************************* FUNCTION DEFINITION ******************************

      Name : print
      Parameters :

      list a(n) person * ( person * )


      Returns: Void type
      Comments:



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      void print ( person * list )
      {

      cout << endl;

      cout << setiosflags ( ios::left );
      cout << setw ( OUTPUT_SPACES ) << "first name"
      << setw ( OUTPUT_SPACES ) << "last name"
      << setw ( OUTPUT_SPACES ) << "id number" << endl << endl;
      while ( list ) //while not at the end of the list
      {
      //output name ect....
      cout << setw ( OUTPUT_SPACES ) << list -> firstName << " " << setw ( OUTPUT_SPACES ) << list -> lastName << " " << setw ( OUTPUT_SPACES ) << list -> idNumber << endl;
      list = list -> next;

      }

      return;
      }

      /******************************* FUNCTION DEFINITION ******************************

      Name : destroyList
      Parameters :

      list a(n) person * ( person * )


      Returns: Void type
      Comments:



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      void destroyList ( person * list )
      {

      person * temp;

      while ( list ) //for each item in the list , destroy the list
      {
      temp = list;
      list = list -> next;
      delete temp;
      }


      return;
      }
      /******************************* FUNCTION DEFINITION ******************************

      Name : key
      Parameters :

      first a(n) person * ( person * ) ,
      second a(n) person * ( person * )


      Returns: char type
      Comments: use a macro for this......



      ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
      char * key ( person * node )
      {

      switch ( sortKey )
      {
      case firstName:
      return node -> firstName;
      case lastName:
      return node -> lastName;
      case idNumber:
      return node -> idNumber;

      };


      }

      input:


      bob johns 222
      suzie barker 333
      adam west 555
      zack wilde 111
      janet woods 444
      qubert johns 666
      barak obama 777
      carly simon 888
      curt cobain 999
      tom gadja 1010
      larry bear 1111
      pilar nuffer 1212
      mikey scalcee 1313
      old puff 1414
      charolette phifer 1515
      don dokken 46464
      adam ant 555
      willodean mcqueen 222
      *

      output ( sorting with first name as key ):


      first name last name id number

      adam ant 555
      adam west 555
      barak obama 777
      bob johns 222
      carly simon 888
      charolette phifer 1515
      curt cobain 999
      don dokken 46464
      janet woods 444
      larry bear 1111
      mikey scalcee 1313
      old puff 1414
      pilar nuffer 1212
      qubert johns 666
      suzie barker 333
      tom gadja 1010
      willodean mcqueen 222
      zack wilde 111
      Press any key to continue
Viewing 2 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.