Reorder an Array according to given Indexes using C++

The following tutorial demonstrates how we can reorder an array according to given indexes using C++. The program attempts to take a random order of indexes and arrange them chronologically.

What is an Array?

An array is a static data structure that contains a group of elements that are indexed from 0. It is a static data structure since it cannot be changed after its declaration and initialization. The memory locations are fixed after the array has been created unlike other dynamic data structures such as Linked Lists.

Arrays are great introductory data structures for beginners in the Data Structures and Algorithms domain (DSA). Multiple operations can be performed on arrays such as deleting elements, reversing elements, sorting the array in ascending and descending order, etc.

Algorithm

The algorithm iterates till the end of the array and keeps swapping the contents of both; the input_Array and the given_indexes array. The following image provides a diagrammatic representation of the logical flow of the algorithm.

Diagram

C++ program to reorder an array according to given indexes

Below is the C++ code for our task:

#include <iostream>
using namespace std;

int main()
{
  int input_Array[] = {110, 80, 150, 20, 100};
  int sizeofArray = sizeof(input_Array) / sizeof(input_Array[0]); 
  int given_indexes[] = {4,3,2,0,1};

  for (int i = 0; i < sizeofArray;i++) {
    while (given_indexes[i] != i)
    {
      swap(input_Array[i], input_Array[given_indexes[i]]);
      swap(given_indexes[i], given_indexes[given_indexes[i]]);
    }
  }
    for (int i = 0;i < sizeofArray;i++)
      cout << input_Array[i] << "," << " ";
}

The program makes use of an important method in C++ i.e :

  • sizeof() – this method returns the size of a variable or a data type. In the following program, the method has been used to calculate the size of the array.

Output:

20, 100, 150, 80, 110,

Leave a Reply

Your email address will not be published. Required fields are marked *