hi,
basically what this program does is reading names from a text file into two dimensional char array and then sort using insertion sort in ascending or descending order depending on user input. i am having trouble coding an "insertion sort function" for this program.
here's the two possible output from console
http://img338.imageshack.us/i/ascending.jpg/
http://img11.imageshack.us/f/descending.jpg/
here is the what i coded so far.
#include <iostream>
#include <fstream>
#include <cstring> //for strcpy and stricmp
using namespace std;
const int MAX_NAMES = 10;
const int MAX_NAME_SIZE = 16;
void printNames(char names[][MAX_NAME_SIZE], int nNames); //function prototypes
void insertionSort(char names[][MAX_NAME_SIZE], int nNames, bool ascending = true);
void swap(int &a, int &b);
int main()
{
char names[MAX_NAMES][MAX_NAME_SIZE] = { 0 }; // local variables
int choice;
bool upordown;
ifstream inputfile; //input file stream object
cout<< "This program opens a text file of names, reads the names and sorts the names in ascending or descending order" << endl;// introduction
inputfile.open("Names.txt"); // open file
if(inputfile.fail())
{
cout<<"Cannot open file"<<endl;
exit(1);
}
for (int i = 0; i < MAX_NAMES; i++) // read file from names.txt
{
for (int j = 0; j< MAX_NAME_SIZE; j++);
{
inputfile >> names[i];
}
}
cout << " Enter 0 for ascending, Enter 1 for descending" <<endl;
cin >> choice; //userinput
while (choice >1 || choice <0)
{
{
cout << " Enter 0 for ascending, Enter 1 for descending" <<endl;
cin >> choice; //userinput
}
}
if (choice == 1)
{
upordown = true;
}
else
upordown = false;
cout << "Before sorting: " << endl;
printNames(names, MAX_NAMES); // ascending or descending ?
insertionSort(names,MAX_NAMES,upordown);
cout << "after sorting: " << endl;
printNames(names, MAX_NAMES);
system("pause"); //pause
return 0;
}
void printNames(char names[][MAX_NAME_SIZE], int nNames) //printnames function
{
for(int i = 0; i < nNames; i++)
{
cout << names[i] << endl; //print names
}
}
void insertionSort(int arr[], int size)
{
int i, j;
for(i = 1; i < size; i++)
{
j = i;
while(j > 0 && arr[j - 1] > arr[j])
{
_swap(arr[j], arr[j - 1]);
j--;
}
}
}
void swap(int & a , int & b) //swap function
{
int temp = a;
a = b;
b = temp;
}