I have an assignment to sort a list of names alphabetically by last name. However, there are three names with the same surname and I can't get the first names to alphabetize with the surnames. Have to code own bubble sort or other sorting algorithm. I chose bubblesort because it's one of the only ones we've learned so far. Any help is appreciated. Everything works except the correct assortment.
Here is my code:
// my name
// Program 6
// This program will show a list of names in a variety of orders.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int size = 25;
void showContacts_FNLN(string fnameArray[], string lnameArray[], int size);
void showContacts_LNFN(string lnameArray[], string fnameArray[], int size);
void reverseContacts_FNLN(string fnameArray[], string lnameArray[], int size);
void reverseContacts_LNFN(string fnameArray[], string lnameArray[], int size);
void searchLasname(string lnameArray[], string fnameArray[], int size);
void searchFirname(string fnameArray[], string lnameArray[], int size);
void bubbleSort(string lnameArray[], string fnameArray[], int size);
int main(int argc, const char * argv[])
{
int count = 0;
int ans;
ifstream nameData;
string lnameArray[size];
string fnameArray[size];
string lname, fname;
nameData.open("names.txt");
while(nameData >> fname >> lname)
{
fnameArray[count] = fname;
lnameArray[count] = lname;
count ++;
}
bubbleSort(lnameArray, fnameArray, size);
while(ans != 9)
{
cout << "What would you like to do?" << endl;
cout << "1) display contacts by first name and last name" << endl;
cout << "2) display contacts by last name and first name" << endl;
cout << "3) display contacts by first name and last name in reverse order" << endl;
cout << "4) display contacts by last name and first name in reverse order" << endl;
cout << "5) search for contact by last name" << endl;
cout << "6) search for contact by first name" << endl;
cout << "9) exit" << endl;
cout << "Enter: ";
cin >> ans;
cout << endl;
switch(ans)
{
case 1: showContacts_FNLN(fnameArray, lnameArray, size); // shows contacts in FN-LN order
break;
case 2: showContacts_LNFN(lnameArray, fnameArray, size); // LN-FN order
break;
case 3: reverseContacts_FNLN(fnameArray, lnameArray, size); // reversed FN-LN order
break;
case 4: reverseContacts_LNFN (fnameArray, lnameArray, size); // reversed LN-FN order
break;
case 5: searchLasname(lnameArray, fnameArray, size); // searches based on LN
break;
case 6: searchFirname(fnameArray, lnameArray, size); // searches based on FN
break;
case 9: cout << "Goodbye!" << endl;
break;
}
}
nameData.close();
return 0;
}
void showContacts_FNLN(string fnameArray[], string lnameArray[], int size)
{
for(int i=0; i<size; i++)
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
}
cout << endl;
}
void showContacts_LNFN(string lnameArray[], string fnameArray[], int size)
{
for(int i=0; i<size; i++)
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
}
cout << endl;
}
void reverseContacts_FNLN(string fnameArray[], string lnameArray[], int size)
{
for(int i=(size-1); i>=0; i--)
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
}
cout << endl;
}
void reverseContacts_LNFN(string fnameArray[], string lnameArray[], int size)
{
for(int i=(size-1); i>=0; i--)
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
}
cout << endl;
}
void searchLasname(string lnameArray[], string fnameArray[], int size)
{
int c = 0;
string slnam;
cout << "Enter a last name: ";
cin >> slnam;
for(int i=0; i<size; i++)
{
if(slnam==lnameArray[i])
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
c++;
}
}
if (c == 0)
{
cout << "There is no match.";
cout << endl;
}
cout << endl;
}
void searchFirname(string fnameArray[], string lnameArray[], int size)
{
int c = 0;
string sfnam;
cout << "Enter a first name: ";
cin >> sfnam;
for(int i=0; i<size; i++)
{
if(sfnam==fnameArray[i])
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
c++;
}
}
if (c==0)
{
cout << "There is no match." << endl;
}
cout << endl;
}
void bubbleSort(string lnameArray[], string fnameArray[], int size)
{
string tmp, tmp2;
//int count=0;
for( int i = 1; i <= size - 1; i++ )
{
for( int j = 0; j < size - i; j++ )
{
//count++;
if( lnameArray[j] > lnameArray[j+1] )
{
tmp = lnameArray[j];
lnameArray[j] = lnameArray[j+1];
lnameArray[j+1] = tmp;
}
if(lnameArray[j] == lnameArray[j+1])
{
if(fnameArray[j] > fnameArray[j+1])
{
tmp = lnameArray[j];
lnameArray[j] = lnameArray[j+1];
lnameArray[j+1] = tmp;
tmp2 = fnameArray[j];
fnameArray[j] = fnameArray[j+1];
fnameArray[j+1] = tmp2;
}
}
}
}
//cout << "count = " << count << endl;
}
Here you go:
void bubbleSort(string lnameArray[], string fnameArray[], int size)
{
for( int i = 0; i < size - 1; i++ )
{
for( int j = 0; j < size - i - 1; j++ )
{
string name1 = lnameArray[j] + fnameArray[j];
string name2 = lnameArray[j + 1] + fnameArray[j + 1];
if(name1.compare(name2) > 0)
{
string tmp = lnameArray[j];
lnameArray[j] = lnameArray[j + 1];
lnameArray[j + 1] = tmp;
tmp = fnameArray[j];
fnameArray[j] = fnameArray[j + 1];
fnameArray[j + 1] = tmp;
}
}
}
}
Instead of having another 'if' for those that have similar last names, I combined the last name and the first name instead then used it for comparison.
I also noticed in your code in for( int j = 0; j < size - i; j++ ) that you forgot to add - 1 after size - i. Once j == size - i - 1 (assuming that i == 0 currently) then you use j + 1 to access an index, this will cause a segmentation fault since you're accessing an index beyond its range.
Your sort doesn't work because you change the position of the last names only (except for the case where two last names are equal.)
You should use a struct to store this information together in one array. Then you can simplify your code a lot:
struct Person {
Person() = default;
Person(string firstname, string lastname) : firstname(std::move(firstname)), lastname(std::move(lastname)) {}
string firstname;
string lastname;
};
void showContacts_FNLN(Person personArray[], int size) {
for (int i = 0; i < size; i++) {
cout << personArray[i].firstname << " " << personArray[i].lastname << endl;
}
cout << endl;
}
void bubbleSort(Person personArray[], int size) {
for (int i = 1; i <= size - 1; i++) {
// The condition must size - i - 1 because otherwise personArray[j+1] is faulty
for (int j = 0; j < size - i - 1; j++) {
if (personArray[j].lastname > personArray[j+1].lastname
|| (personArray[j].lastname == personArray[j+1].lastname &&
personArray[j].firstname > personArray[j+1].firstname)) {
auto tmp = std::move(personArray[j]);
personArray[j] = std::move(personArray[j+1]);
personArray[j+1] = std::move(tmp);
}
}
}
}
int main(int argc, const char * argv[]) {
int count = 0;
ifstream nameData;
Person personArray[size];
string lname, fname;
nameData.open("names.txt");
while(nameData >> fname >> lname) {
personArray[count] = Person(fname, lname);
count++;
}
nameData.close();
bubbleSort(personArray, size);
showContacts_FNLN(personArray, size);
return 0;
}
I removed some non-essential parts from this example to keep it very short but you should get the idea. (Note that my code makes use of C++11 move semantics, if this confuses you, just remove them.)
Some more suggestions:
Do not use using namespace std;. (The internet will tell you why.)
If you can, use std::array, which eliminates the need to always pass the size of the arrays and allows you to use a C++11 range for loop.
Related
I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}
For an assignment, we were to fill an array with user-defined characters that stops filling once the user enters a full stop ".". Part of the assignment is to print out the characters entered in the array in reverse, but what I have seems to just print nothing.
First time asking, so apologies if it's a silly question. Thanks in advance.
#include <iostream>
using namespace std;
//Function declarations
bool fillArray(char charArray[], int arraySize, int& numberUsed);
void outputInReverse(const char charArray[], int& numberUsed);
int main() {
const int arraySize = 100;
char charArray[arraySize] = { };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
}
//Function definitions
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
charArray[index] = inputChar;
//How many entries made
numberUsed = i;
count++;
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count - 1) << endl;
return count;
}
}
}
if (numberUsed == arraySize) {
arrayFull = true;
return arrayFull;
}
return sentinelEntered;
return count;
}
// Reverse
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed; i > 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
FILLING ARRAY....
Enter up to 100 character values. Enter full stop to end. Enter char 1:
a
Enter up to 100 character values. Enter full stop to end. Enter char 2:
b
Enter up to 100 character values. Enter full stop to end. Enter char 3:
c
Enter up to 100 character values. Enter full stop to end. Enter char 4:
d
Enter up to 100 character values. Enter full stop to end. Enter char 5:
e
Enter up to 100 character values. Enter full stop to end. Enter char 6:
.
Number of entries: 5
ARRAY OUTPUT....
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Not sure what you are trying to return from fillArray(), but since its a bool type, assuming you are trying to return if the array is empty or not. Observe added comments to see corrections.
int main() {
const int arraySize = 100;
//corrected
char charArray[arraySize] = { NULL };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
return 0;
}
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to
end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
//corrected: shifted here so before '.' can enter into array we return
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count) << endl;
//correction: update numberUsed before returning and no of
//elements = count
numberUsed = i;
return count;
}
//correction: array index should not be "index" but i
charArray[i] = inputChar;
//How many entries made
numberUsed = i;
count++;
}
}
if (numberUsed == arraySize)
return true;
return false;
}
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed-1; i >= 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
My apologies for being a little vague about the issue(s) in the topic, but I really am not sure. I am attempting to create a course_directory as a lab project for school, and up until now everything had been progressing quite well. I have written and tested each of the function in the main.cpp before attempting to move the class functions into the .hpp file. My goal is to have nothing in main except for a call to "Run" that will open a file, and in turn make a call to "displayMenu", and allow the user to interact with the information as they choose, but now everything is compiling correctly, and nothing is being displayed.
Course_directory.hpp
#include "Course_Directory.h"
using namespace std;
Course_Directory::Course_Directory(){};
Course_Directory courses[1001];
void Course_Directory::displayMenu(){
cout << "1.Print all courses" << endl;
cout << "2.Print all courses for a department" << endl;
cout << "3.Print roster for a course" << endl;
cout << "4.Print the largest class" << endl;
cout << "5.Swap two classes" << endl;
cout << "6.Print schedule for a student" << endl;
cout << "7.Exit" << endl;
char dept[50], dept2[50];
int courseNo, courseNo2, i, choice;
while (choice != 7) {
cout << "\nEnter your choice: ";
cin >> choice;
if (choice == 1)
printAllCourses(i);
else if (choice == 2) {
cout << "\nEnter department name:";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
coursesInDept(dept, i);
}
else if (choice == 3) {
cout << "\nEnter course number:";
cin >> courseNo;
studentsInCourse(courseNo, i);
}
else if (choice == 4) {
largestClass(i);
}
else if (choice == 5) {
cout << "\nEnter first department name :";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
cout << "\nEnter first course number: ";
cin >> courseNo;
cout << "\nEnter second department name :";
cin >> dept2;
for(int k = 0; k < sizeof(dept2); k++)
{
dept2[k] = (toupper(dept2[k]));
}
cout << "\nEnter second course number: ";
cin >> courseNo2;
swap2(dept, courseNo, dept2, courseNo2, i);
}
else if (choice == 6) {
int id;
cout << "\nEnter a student Id:";
cin >> id;
schedule(id, i);
}
}
cout << "Goodbye!\n";
}
void Course_Directory::printAllCourses(int len){
for (int i = 0; i < len; i++)
cout << "Course name: " << courses[i].courseName << ", Course
number: " << courses[i].courseNum << endl;
cout << len;
}
void Course_Directory::coursesInDept(char *dept, int len) {
for (int i = 0; i < len; i++)
if (strcmp(dept, courses[i].courseName) == 0)
cout << "Course Name: " << courses[i].courseName << ",
Course number: " << courses[i].courseNum << endl;
}
void Course_Directory::studentsInCourse(int courseNo, int len) {
for (int i = 0; i < len; i++)
if (courseNo == courses[i].courseNum) {
for (int m = 0; m < courses[i].numStudents - 1; m++)
cout << courses[i].IDs[m] << ",";
cout << courses[i].IDs[courses[i].numStudents - 1] <<
endl;
}
}
void Course_Directory::largestClass(int len) {
int max = -999;
for (int i = 0; i < len; i++) {
if (courses[i].numStudents > max)
max = courses[i].numStudents;
}
for (int i = 0; i < len; i++) {
if (courses[i].numStudents == max){
cout << "\nThe largest class is in department: " <<
courses[i].courseName
<< ", and the course number is: " << courses[i].courseNum
<< "\n";
cout << "The class currently has " << max << " students
enrolled.\n";
}
}
}
void Course_Directory::swap2(char *firstDep, int firstNo, char
*secondDep, int secondNo, int len) {
Course_Directory temp;
int firstIndex, secondIndex;
for (int i = 0; i < len; i++) {
if (strcmp(firstDep, courses[i].courseName) == 0 &&
courses[i].courseNum == firstNo)
firstIndex = i;
if (strcmp(secondDep, courses[i].courseName) == 0 &&
courses[i].courseNum == secondNo)
secondIndex = i;
}
temp = courses[firstIndex];
courses[firstIndex] = courses[secondIndex];
courses[secondIndex] = temp;
}
void Course_Directory::schedule(int id, int len) {
cout << "Courses student " << id << " is enrolled in: " << endl;
for (int i = 0; i < len; i++) {
for (int j = 0; j < courses[i].numStudents; j++)
if (courses[i].IDs[j] == id)
cout << courses[i].courseNum << " \n";
}
}
Course_Directory.h
#ifndef COURSE_DIRECTORY_H
#define COURSE_DIRECTORY_H
#include <iostream>
using namespace std;
class Course_Directory{
private:
int* deptSize;
string filename;
public:
char courseName[1001];
int courseNum;
int numStudents;
int IDs[1001];
int* choice;
void displayMenu();
Course_Directory();
//Course_Directory(const Course_Directory& original);
//~Course_Directory();
//void run(string);
void coursesInDept(char*, int);
void studentsInCourse(int, int);
void largestClass(int);
void swap2(char*, int, char*, int, int);
void schedule(int, int);
void printAllCourses(int);
};
#include "Course_Directory.hpp"
#endif //COURSE_DIRECTORY_H
main.cpp
#include "Course_Directory.h"
using namespace std;
class Course_Directory;
int main() {
ifstream file;
file.open("input.txt");
char *token;
int i = 0, j;
Course_Directory courses[100];
if (!file.fail()) {
std::string line;
while (getline(file, line)) {
j = 0;
char *str = const_cast<char *>(line.c_str());
token = strtok(str, " ");
while (token != NULL)
{
if (j == 0)
strcpy(courses[i].courseName, token);
else if (j == 1)
courses[i].courseNum = atoi(token);
else if (j == 2)
courses[i].numStudents = atoi(token);
else
courses[i].IDs[j - 3] = atoi(token);
j++;
token = strtok(NULL, " ");
cout << courses[i].courseName << endl;
}
i++;
}
file.close();
}
else{
cout << "File not found." << endl;
}
//menu
Course_Directory displayMenu();
return 0;
}
If I leave Course_Directory off of displayMenu(); then I get "displayMenu" was not declared in this scope. I'm not sure what the problem is or why the menu will not display. Any help would be greatly appreciated!
(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}
Count all the records from the file "8.dat". To read each individual recording perform dynamic memory capture.
Sort the records to different keys:
Item number (ascending);
The cost (descending);
Number of stock (descending).
Use selection sort
Total sorting will be done 12 times, each time the array is sorted in its original condition.
For each case count of comparisons to and permutations.
Below code implements insertion sort. Twice, without saying so much.
I need to use selection sort. How to do selection sort?
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
struct PRICE
{
int number;
char name[20];
int cost;
int quantity;
} *pm;
int Menu();
void PrintPRICE(PRICE);
void sort_cost(PRICE*, int);
void sort_quantity(PRICE*, int);
long file_size(const char*);
int main()
{
int count = 0;
const char *fname = "D:\8.dat";
FILE* file = fopen(fname, "r");
if (file != NULL)
{
long size = file_size(fname);
count = size / sizeof PRICE;
pm = new PRICE[count];
fread(pm, sizeof PRICE, count, file);
fclose(file);
}
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
int ch = Menu();
switch (ch)
{
case 1:
{
sort_cost(pm, count);
cout << endl;
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
case 2:
{
sort_quantity(pm, count);
cout << " Result: " << endl;
cout << "-----------------------" << endl;
for (int i=0; i<count; i++)
{
PrintPRICE(pm[i]);
cout << endl;
}
break;
}
default: break;
}
delete [] pm;
_getch();
}
void PrintPRICE(PRICE price)
{
cout << " Product: " << price.name << endl;
cout << " Number of orden: " << price.number << endl;
cout << " Product cost: " << price.cost << endl;
cout << " Quantity in stock: " << price.quantity << endl;
cout << "-----------------------------------n" << endl;
}
long file_size(const char* filename)
{
FILE *Pfile = NULL;
Pfile = fopen(filename, "rb");
fseek(Pfile, 0, SEEK_END);
long size = ftell(Pfile);
fclose(Pfile);
return size;
}
void sort_cost(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (i>=0 && array[i].cost>key.cost)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = key;
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
void sort_quantity(PRICE* array, int count)
{
int change = 0;
int comparesion = 0;
for (int i=1; i<count; i++)
{
PRICE key = array[i];
int j = i - 1;
comparesion++;
while (j>=0 && array[i].quantity>key.quantity)
{
array[j + 1] = array[j];
j = j - 1;
change++;
}
array[j + 1] = array[j];
}
cout << "n Quantity change: " << change << endl;
cout << " Quantity comparesion: " << comparesion << endl;
}
int Menu()
{
int n;
cout << " 1 - Sort by cost" << endl;
cout << " 2 - Sort by quantity" << endl;
cout << "n Your choice: "; cin >> n;
return n;
}
source code for the selection sort
void selectSort(int arr[], int n)
{
int pos_min,temp;
for (int i=0; i < n-1; i++)
{
pos_min = i;
for (int j=i+1; j < n; j++)
{
if (arr[j] < arr[pos_min])
pos_min=j;
}
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}