A common programming problem is maintaining a list in numerical or alphabetical order. For example, inventory part
Question:
A common programming problem is maintaining a list in numerical or alphabetical order. For example, inventory part numbers are typically kept in numerical order, but telephone lists are kept in alphabetical order. For this exercise, write a function that inserts a three-digit part number code in a list of part numbers. The list is maintained in increasing numerical order, and duplicate part numbers aren’t allowed. Allocate a maximum list size of 100 values, and use a sentinel value of 9999 to indicate the end of the list. For example, if the current list contains nine part numbers, the 10th position in the list contains the sentinel value. Figure 7.13 shows the insertion process for an original list of nine part numbers, using the following processing algorithm:
Determine where in the list the new part number should be placed This is done by comparing the new part number with each value in the current list until a match is found, a part number larger than the new code is located, or the end of the list is encountered If the new part number matches an existing part number, display a message that the part number exists Else To make room for the new element in the array, move each element down one position This is done by starting from the sentinel value and moving each item down one position until the desired position in the list is vacated Insert the new part number in the vacated position EndIf
109, 122, 136, 144, 157, 162, 178, 185, 192, 9999 a) original list
109, 122, 136, 142, 144, 157, 162, 178, 185, 192, 9999 b) updated list when inserted 142
THIS IS WHAT I HAVE SO FAR
#include <iostream>
using namespace std;
int main()
{
int values[100] = { 109, 122, 136, 144, 157, 162, 178, 185, 192, 9999 };
int val;
cout << "Please enter a three digit value " << endl;
cin >> val;
if (val < 100 || val > 999)
{
cout << "Invalid value to update list";
system("PAUSE");
exit(0);
}
for (int i = 0; i < 100; i++)
{
while (values[i] != 9999)
{
if (val == values[i])
{
cout << " value already in list " << endl;
}
else if (values[i] > val)
{
for (int j = 98; j > i; j--)
{
values[j] = values[j+1];
}
values[i] = val;
}
}
}
system("PAUSE");
return 0;
}
Modern Database Management
ISBN: 978-0133544619
12th edition
Authors: Jeff Hoffer, Ramesh Venkataraman, Heikki Topi