The C++ Index Sort

Published on: February 28, 2011

In this tutorial, I show you the index sort in c++. Last time I showed you the Bubble Sort which is good for sorting one array but it's still very inefficient because it moves the data within the array subscripts which can take a lot of processing power. The index sort however, just moves the subscripts around based on your sorting specifications. This allows you to sort multiple arrays (parallel arrays) with ease. The Index Sort is efficient and it is the preferred method of sorting when you have a lot of data in more than one set of arrays. This tutorial is very simple and builds on my bubble sort tutorial and uses only 2 arrays. In a future tutorial, I hope to show you the index sort using more arrays and using functions. 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
//Website: EasyProgramming.net

#include <iostream>
#include <string>

using namespace std;

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

 for(i=0;i<=6;i++)
 {
  cout << "Please enter name: ";
  cin >> name[i];
  cout << "Please enter grade: ";
  cin >> grade[i];
 }

 for(i=0;i<=6;i++)
 {
  index[i]=i;
 }

 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;
   }
  }
 }
 cout << endl;

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

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

 //system("pause");
}



Comments: