Use the Index Sort in a Function

Published on: March 11, 2011

In this tutorial, I show you the index sort in c++ using void functions. Last time I showed you the index Sort which is good for sorting multiple arrays but in one main program. This tutorial breaks down the index tutorial from last time into three sections where we declare the functions, the main program, and the implementation of the functions.

This tutorial is a sort of foundation for what's to come in my near future videos. I will show you how to use header (.h) files in C++ as well as implementation files which are other C++ files in the same program folder. It's very helpful and a great way to program because it can be very organized. That will hopefully come very soon.

If you have any questions about the program or anything in general relating to beginner C++ Programming, feel free to ask. I hope you enjoy the video and if you have any requests feel free to let me know.

Remember to checkout the Codesnip below to review the C++ code yourself! Feel free to copy the code, but I ask that you please provide credit if you leave the code unchanged when you use it.

Codesnip:

//Name:  Nazmus
//Program: Index Sort with Functions
//Website: EasyProgramming.net

#include <iostream>
#include <string>

using namespace std;

void prompt(string name[7], int grade[7]);
void init(int index[7]);
void sort(string name[7], int index[7]);
void output(string name[7], int grade[7], int index[7]);

int main()
{
 string name[7];
 int grade[7];
 int index[7];

 prompt(name, grade);
 init(index);
 sort(name, index);
 output(name, grade, index);
}

void prompt(string name[7], int grade[7])
{
 for(int i=0;i<=6;i++)
 {
  cout << "Please enter name: ";
  cin >> name[i];
  cout << "Please enter grade: ";
  cin >> grade[i];
 }
}

void init(int index[7])
{ 
 for(int i=0;i<=6;i++)
 {
  index[i]=i;
 }

}

void sort(string name[7], int index[7])
{
 int i, j;
 for(i=0;i<=5;i++)
 {
  for(j=i+1;j<=6;j++)
  {
   int temp;
   
   if(name[index[i]] > name[index[j]])
   {
    temp = index[i];
    index[i] = index[j];
    index[j] = temp;
   }
  }
 }
}

void output(string name[7], int grade[7], int index[7])
{
 int i;
 cout << endl;

 for(i=0;i<=6;i++)
 { 
  cout << name[index[i]] << "        "
   << grade[index[i]] << endl;
 }

 cin.ignore();
 cin.get();

 //system("pause");
}



Comments: