please help with insertion sort

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Sep 2004
Posts: 7
Reputation: christyj5 is an unknown quantity at this point 
Solved Threads: 0
christyj5 christyj5 is offline Offline
Newbie Poster

please help with insertion sort

 
0
  #1
Nov 6th, 2005
I am trying to do an insertion sort that reads from a file it has it own class but i can not get the program to do anything it says no errors but crashes when i try to run
  1. #include <string>
  2.  
  3. using namespace std;
  4.  
  5. class Student {
  6. public:
  7. string lastname;
  8. string firstname;
  9. string credittakings;
  10. string creditearned;
  11. string gradepoint;
  12. Student * next;
  13.  
  14.  
  15. private:
  16. Student(string lname,string fname,string credittakings,string creditearned,string gradepoint);
  17. void set_next(Student *);
  18. Student* get_next();
  19. //bool operator > (Student& op1);
  20.  
  21. void print_output();
  22. };
  23.  
  24. void Student::print_output()
  25. {
  26. cout <<" ******************************** " << endl;
  27. cout << "LastNAME " << " " << lastname << endl;
  28. cout << "FirstName" << " " << firstname << endl;
  29. cout << "CreditTakings" << " " << credittakings << endl;
  30. cout << "CreditEarned " << " " << creditearned << endl;
  31. cout << "GradePoint " << " " << gradepoint << endl;
  32. }
  33.  
  34.  
  35.  
  36. #include <iostream>
  37. #include "string"
  38. #include "student.h"
  39. #include <fstream>
  40. using namespace std;
  41.  
  42.  
  43.  
  44. Student* list[20];
  45.  
  46. int main()
  47. {
  48. string lastname;
  49. string firstname;
  50. string credittakings;
  51. string creditearned;
  52. string gradepoint;
  53.  
  54.  
  55. //fstream inFile("students.txt");
  56. ifstream inFile("students.txt");
  57. //3 ofstream outFile; //output file stream variable
  58. //outFile.open("output10p1.txt"); //open outfile
  59.  
  60. //check if file opened
  61. if (!inFile)
  62. {
  63. cout<< "Can not open file student.txt"<<endl;
  64. return 0;
  65. }
  66. //declare variables
  67. char str[128];
  68. int i=0, c;
  69.  
  70. while (!inFile.eof())
  71. {
  72. inFile.getline(str, 128);
  73. string line = str;
  74. int pos1 = line.find(",");
  75. string lastname = line.substr(0,pos1);
  76. int pos2 = line.find(",",pos1+1);
  77. string firstname = line.substr(pos1+1,pos2-pos1-1);
  78. int pos3 = line.find(",",pos2+1);
  79. string credittakings = line.substr(pos2+1,pos3-pos2-1);
  80. string creditearned = line.substr(pos3+1,line.length()-pos3-1);
  81. //int pos4=line.find(",",pos3+1);
  82. //string gradepoint = line.substr(pos4+1,line.length()-pos4-1);
  83. //string gradepoint = atof(grade.c_str());
  84.  
  85.  
  86.  
  87. //list[i] = new Student;
  88. list[i] ->lastname = lastname;
  89. list[i] ->firstname = firstname;
  90. list[i] ->credittakings = credittakings;
  91. list[i] ->creditearned = creditearned;
  92. list[i] ->gradepoint= gradepoint;
  93. i++;
  94.  
  95. }
  96. // SAVE THE CURRENT VALUE OF THE LOOP COUNTER. IT'S THE STUDENTS COUNT
  97. int count = i;
  98.  
  99. // loop will keep function until user enters "0"
  100. while (true)
  101. {
  102. //(0 to quit)
  103. cout<<"Which column would you like to sort by (0 to quit) ==> "<<endl;
  104. cout<<"1) Last Name"<<endl<<"2) first Name"<<endl;
  105.  
  106. cin>>c;
  107.  
  108. // if "0" is entered loop will terminate
  109. if (c == 0)
  110. break;
  111.  
  112. // Loop Runs Til Count == Number Of Students Read
  113. for (i=0; i < count; i++)
  114. {
  115. for (int j=i+1; j < count; j++)
  116. {
  117.  
  118. switch (c)
  119. {
  120. case 1: if (list[i]->lastname > list[j]->lastname){
  121. Student* tmp = list[i];
  122. list[i] = list[j];
  123. list[j] = tmp;
  124. break;
  125. }
  126. case 2: if (list[i]->firstname > list[j]->firstname){
  127. Student* tmp = list[i];
  128. list[i] = list[j];
  129. list[j] = tmp;
  130. break;
  131. }
  132.  
  133.  
  134. }
  135.  
  136. }
  137.  
  138. }
  139. cout <<"+-----------+-------------+---------------------+------------------------------------------------+"<<endl;
  140. cout <<"|Last Name | First Name | CreditTakings | CreditEarned | GradePoint|"<<endl;
  141. cout <<"+-----------+-------------+---------------------+------------------------------------------------+"<<endl;
  142.  
  143. // statement to output sorted table
  144. for (i=0; i< count; i++)
  145. {
  146. cout <<list[i]->lastname<<"\t | "<<list[i]->firstname<<"\t | "<<list[i]->credittakings<<"\t| ";
  147. cout <<list[i]->creditearned<<"\t |"<< list[i]->gradepoint<<"\t |"<< endl;
  148. }
  149. cout <<"+-----------+-------------+---------------------+--------------------+"<<endl;
  150.  
  151.  
  152. }
  153. return 0;
  154. }
the text file is
  1. Johnson Christy 12 85 2.5
  2. Lewis Breana 15 45 3.2
  3. Adams Brittany 13 25 4.0
  4. Mcallister Terrance 16 90 3.7
  5. Johnson Darius 14 25 2.0
<< moderator edit: added code tags: [code][/code] >>
Last edited by Dave Sinkula; Nov 6th, 2005 at 4:18 pm.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 148
Reputation: Micko is on a distinguished road 
Solved Threads: 6
Micko Micko is offline Offline
Junior Poster

Re: please help with insertion sort

 
0
  #2
Nov 7th, 2005
Maybe you shoud read sorting tutorial from
www.eternallyconfuzzled.com
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,688
Reputation: Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all 
Solved Threads: 265
Lerner Lerner is offline Offline
Posting Virtuoso

Re: please help with insertion sort

 
0
  #3
Nov 7th, 2005
I view programming as a four step process. First I have to have the inspirition to start a project (or it is something I'm forced to do). Second, I have to think my through the project, usually ruining several pages of paper filled with failed algorithms. Third I write the program. And fourth I debug the program. Except, that I try to do step three and four at the same time. How? By writing a single function at a time, and more often only a few lines at a time, and debugging them before moving on. Even then, I often get an entire program to compile but it hangs, or it fails to develop the correct answer to known scenarios, or fails in some other fashion because I don't find all the bugs in my code, or flaws in my logic for that matter, by the time I'm done writing the code. That's when the hard stuff starts--run time debugging. I usually start by commenting out funtctions until I get back to a state that does do what I want and focus on the implicated function. Now, I don't do this for a living, and I don't have class projects I have to complete on time, so I can usually putz my way through things, but I suspect that many successful programmers use a similar process to complete their projects. SO, what I'd recommend is go back to the beginning and start from scratch again OR start from the end and work your way back. Either way, you'll benefit by using a debugger to follow variables through from one step to the next, or start adding a bunch of output statement to make sure the values are as expected each step along the way. When you've narrowed down the problem it's easier to find a solution on your own, or to ask a focused question so others can help you in an efficient and satisfying manner.

Good luck.
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 4,364
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 242
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: please help with insertion sort

 
0
  #4
Nov 7th, 2005
This is an array of 20 pointers to Student.
  1. Student* list[20];
Where do you allocate memory for each of these 20 pointers?

Or did you instead mean to make an array of 20 Students? That would be like this.
  1. Student list[20];
But your use of -> notation would then need to be changed to . instead. There would need to be other changes as well to get it to compile.
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7
Reputation: christyj5 is an unknown quantity at this point 
Solved Threads: 0
christyj5 christyj5 is offline Offline
Newbie Poster

Re: please help with insertion sort

 
0
  #5
Nov 8th, 2005
I tried to start over and read the example in the book but I am getting errors with this program .


#include <iostream.h>
#include <iomanip.h>
#include <string>
#include <fstream>
using namespace std;

struct student
{
string creditearned;
string a [100];
string credittaking;
string gradepoint;
string lastname;
string firstname;
};





void insert(student x[], const int n)
{
// insert element n in proper location
// in an array whose elements 0..n-1
// are already in ascending order
student t=x[n]; // element to be inserted
// move elements larger than t forward
int i;
for (i = n-1; i >= 0 && x[i] > t; i--)
x[i+1] = x[i];
// put t in last vacated location
x[i+1] = t;
}

void inssort(student x[], const int size)
{
// sort array of size elements into ascending order
// Starting with sorted part length 1, insert each
// successive element into proper location
for (int i=1; i<size; i++) insert(x, i);
}

//int readArray(double x[], const int max)
//{
// read up to MAX elements into array, throwing exception
// if limit exceeded. Return number of elements read.

int loadarr(student a[], int MAX)
{
// load phone directory from the file
// /home/sjmccasl/pub/cmsc204/phonenum.dat
// does no error checking. The file is assumed to
// exist and have the proper layout.
#ifdef _M_IX86
// Borland and Visual read file from current folder
ifstream inp("students.txt");
#endif
int count(0); string lastname;
while (inp >> lastname)
{
if (count >= MAX) throw 1;
a[count].lastname = lastname;
inp >> a[count].firstname;
inp >> a[count].creditearned;
inp >> a[count].credittaking;
inp >> a[count++].gradepoint;
}
return count;
}

//double t;
//int i(0);
//while (cin >> t)
//{
//if (i >= max) throw 1;
//x[i++] = t;
//}
//return i;
//}

void printarr(student a[], const int size)
// print an array of doubles in fixed format, D decimal positions,
// E elements, each C columns wide, to a line
{
for (int i = 0; i<size; i++)

cout<< setw(20)<< a[i].lastname+ " " + a[i].firstname<< "\t" << a[i].creditearned <<"\t" << a[i].credittaking<< "\t" << a[i].gradepoint<< endl;
}
int main()
{


int size;
student a[100];
size = loadarr(a, 100);
cout << endl;
printarr(a, size);
inssort(a, size);
cout << "sorted" << endl;
printarr(a, size);
return 0;
}
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,688
Reputation: Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all Lerner is a name known to all 
Solved Threads: 265
Lerner Lerner is offline Offline
Posting Virtuoso

Re: please help with insertion sort

 
0
  #6
Nov 9th, 2005
When I think of an insertion sort I think of starting with a collection of unsorted items (say array a) and I sort them as I insert them into a second collection (say array b). That means I need some attribute to do the sorting--in this case the last name seems to be a reasonable. Thus if the first student in a was Jones I'd put that in the first element of the array b. If the second student was Smith I'd put it in the second element of the array b. If the third student was Miller I'd put it between Jones and Smith in b. By the time I got done with array a, array b will be sorted by last name and I could read array b back into array a. Alternatively, I could just insert appropriately into array a as I was reading in from the file, and save myself a number of steps, but that may not be possible in your case.

To accomplish that task with code I'd look at each student's last name in the array busing a loop. As soon as I found a name (at position n) that comes after the one I'm trying to put into the array b alphabetically, I want to move all names from position n to the end of the array b to the right by one starting with the last name already in array b, and then insert the current student from array a into array b at position n. Thus, to do an insertion sort I would need the array (or another container) to insert into, the student to insert, the position of the desired insertion in array b and the number of students in array b already.
Reply With Quote Quick reply to this message  
Join Date: May 2004
Posts: 178
Reputation: jim mcnamara is on a distinguished road 
Solved Threads: 10
jim mcnamara jim mcnamara is offline Offline
Junior Poster

Re: please help with insertion sort

 
0
  #7
Nov 14th, 2005
I'm posting this very small insertion sort routine in C - well after your post, and possibly a homework deadline, so you can see what one looks like.

  1. typedef THING unsigned long;
  2. /* n= number of elements in *input */
  3. void insertion(THING *input, int n)
  4. {
  5. int i=0, j=0;
  6. THING tmp=0;
  7. for (i = 1; i < n; i++)
  8. {
  9. tmp = input[i];
  10. j = i;
  11. while ((j > 0) && (input[j-1] > tmp))
  12. {
  13. input[j] = input[j-1];
  14. j--;
  15. }
  16. input[j] = tmp;
  17. }
  18. }
It's really like a deferred "swap" function - you swap only after
you find where the element belongs.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC