Programming in C++

Array Type Problems

One-Dimensional Arrays

An array is a group of related data values that are all of the same type. There are a couple of reasons why a programmer might want to use an array in a program. One motivation for using an array is the reduction of identifiers. For example, suppose you have a problem where you need to store the values of fifty test scores. Without arrays, you would have to declare fifty variables in order to keep track of all of their individual scores (test1, test2, test3, ..., test50). With arrays, you could simply declare an array that would hold fifty elements, such as int test[50]. The individual test scores are not given different names in the array. Instead, they are named test as a group of related values. When you want to access a particular text score, you have to use a subscript (or technically speaking, an index value), such as test[0] for the first test, test[1] for the second test, and so on. The first element in an array is also given an index value of 0 and then the index is incremented for each new element.

The form of declaring an array is as follows:

   type arrayName[MAX];

where MAX is the maximum number of elements. In the above example,

   int test[50];

would be an appropriate array declaration. You can also initialize arrays by using curly braces { } as follows:

   int test[5] = { 1, 2, 3, 4, 5 };

This intializes test[0] to 1, test[1] to 2, test[2] = 3, test[3] = 4, and test[4] = 5.

You can initialize all of the elements in an array to 0 as follows:

   int test[50] = { 0 };

Another reason for using an array is if you are faced with a problem where you need to use/access the data involved more than once. In the above example, that could easily be accomplished by using an array because we could use the index value of each test to access each test however many times we need to. When processing an array, it is best (at least from my point of view) to use a for loop. For loops are good to use when processing arrays because when dealing with an array we know exactly how many times when need to run through the loop (MAX - 1).

Example 1: Here is a little example of storing values into an array from a text file and calculating the average value. NOTE: The text file contains one value per line.

////////////////////////////////////////////////////////////////////////////////////

   const int MAXSIZE = 100;
   double salesAmount[MAXSIZE]; // declaration for array
   double aSalesAmount;
   int count = 0;
   double total = 0.0;
   double average;
   ifstream myFile; // declaring input file

   myFile.open ( "C:\\DATA.RPT" );
   if ( !myFile )
   {
           cout << "Error opening input file: C:\\DATA.RPT";
           system("PAUSE");
           exit(1);
   }

   while ( !( myfile.eof ( ) ) )
   {
           myFile >> aSalesAmount >> ws;
           total += aSalesAmount;
           salesAmount[count] = aSalesAmount;
           count++;
   } // end while

   if ( count != 0 )
           average = total / count;
   else
           average = 0.0;

   myFile.close ( );

////////////////////////////////////////////////////////////////////////////////////

Example 2: Having performed the above piece of code, suppose we want to list (and count) the values that are above the average (display to screen).

Add the following to the declaration and initialization section:

   int numAboveAvg = 0;
   int k;

Add the following to existing code:

   cout << "Sales Amount that are above the average [" << average << "] are as follows: " << endl << endl;

   for ( k = 0; k < count; k++ )
           if ( salesAmount[k] > average )
           {
                       numAboveAvg++;
                       cout << salesAmount[k] << endl;
           }

   cout << endl << endl << "There are " << numAboveAvg << " values above the average." << endl;



The following is a simple program demonstrating the use of a one-dimensional array:

/////////////////////////////////////// Compiled Using Dev-C++ Compiler /////////////////////////////////////

#include <iostream.h>
#include <stdlib.h>

const int MAXSIZE = 5;

int main()
{
     int accountNumbers[MAXSIZE];
     int customerNum = 1;
     int count = 0;

     cout << endl;
     for (int k = 0; k < MAXSIZE; k++)
     {
           cout << "Enter customer account number (####) for customer " << k+1 << ": ";
           cin >> accountNumbers[k];
     }

     cout << endl << endl;
     while (count < MAXSIZE)
     {
           cout << "Customer " << customerNum << " account number = " << accountNumbers[count] << endl;
           customerNum++;
           count++;
     }
     cout << endl << endl;

     system("PAUSE");
     return 0;
}// end main()

/////////////////////////////////////// Compiled Using Dev-C++ Compiler /////////////////////////////////////


With the very basics of a one dimensional array out of the way, we can now move on and talk about two dimensional arrays, which are more powerful than 1D arrays. Read on for more...

Two Dimensional Arrays

If you are not familiar with one-dimensional arrays, you should back up and read that section before reading this one, [see One-Dimensional Arrays]. While one-dimensional arrays allow data to be placed in an array one row at a time, two-dimensional arrays are capable of storing data in rows and columns. Each row in the array is associated with however many columns you have defined for the array. The only drawback is the fact that the entire array must contain elements of the same type, which is defined when you declare the array. Because of the capability of storing data in rows and columns, it is obvious that two-dimensional arrays can be a very powerful tool in programming compared to one-dimensional arrays. Declaring a two-dimensional array is this simple:

   type arr-name[numRows][numCols];

where type is the data type for the array, arr-name is the variable name for the array, numRows is the maximum number of rows for the array, and numCols is the maximum number of columns for the array. If you wish to declare an integer array of five rows and three columns, you could use:

   int arr[5][3];

If you wish to initialize the values in the array during compile time, you could use:

   int arr[5][3] =
   {
       { 0, 1, 2 }
       { 3, 4, 5 }
       { 6, 7, 8 }
       { 9, 0, 1 }
       { 2, 3, 4 }
   }

The above code initializes arr[0][0] = 0, arr[0][1] = 1, arr[1][0] = 3, arr[1][1] = 4, arr[4][0] = 2, and so on. Because 2D arrays must be filled by row and column, processing a 2D array involves using nested for loops. For instance, in order to fill an array declared numArr[10][10] with user input, you could use the following code:

   for (int rows = 0; rows < 10; row++)
       for (int cols = 0; cols < 10; cols++)
       {
               cout << "Enter a value for row " << row+1 << " col " << col+1 << ": ";
               cin >> numArr[row][col];
       }


If you want to display the contents of the above filled array ten values per line, you could use the following code:

   for (int rows = 0; rows < 10; row++)
   {
       for (int cols = 0; cols < 10; cols++)
               cout << numArr[row][col];
       cout << endl;
   }



Another common use of 2D arrays is storing a collection of strings. When storing strings in a 2D array, the rows of the array are associated with the position of the full string value, but the columns of the array are actually associated with the individual characters of the string. For instance, if the string "c++" was stored in row 0 of stringArr, then stringArr[0][0] would hold 'c', stringArr[0][1] would hold '+', and stringArr[0][2] would hold '+'. For example, suppose we have a 2D array declared as follows:

   char stuNames[30][26];

This array would hold 30 strings with a maximum of 25 characters for each string length (I declared the array with 26 maximum columns to have enough room for the null terminater '\0' that is attached to the end of a string). Suppose we want to fill the array with values from a text file we have previously opened that contains one string per line of 25 characters, and we know the file contains no more than 30 lines of data but we don't know exactly how many. I'll call the logical file name of the input file myFile. If you are not familiar with text files, [see Working with Text Files (section 6)]. Code to take care of this situation is as follows:

   sizeOfFile = 0;
   for (int rowData = 0; rowData < 30; rowData++)
   {
       myFile.get(stuNames[rowData], 26) >> ws;
       sizeOfFile++;
   }


We could display the contents of our filled string array one value per line as follows:

   for (int rowData = 0; rowData < sizeOfFile; rowData++)
       cout << stuNames[rowData] << endl;


2D array Example 1:
Suppose we have a 2D integer array of exactly ten rows and ten columns, and we need to find the sum of the integers along the main diagonal of the array. We could use the following piece of code:

   int arr[10][10];
   .
   .
   arr gets values
   .
   .
   int sum = 0;
   for (int row = 0; row < 10; row++)
       for (int col = 0; col < 10; col++)
               if (row == col)
                       sum += arr[row][col];

   cout << "The sum of the values along the main diagonal is: " << sum << endl;


2D array Example 2:
Suppose the correct answers for a true/false quiz are: T T F F T
Suppose a 2D array contains the student answers with each row representing the responses of a particular student. The first row (0) of the array contains the above answer "key".
Write code to calculate the student's scores on the quiz and store these scores in a one-dimensional array. Assume each question is worth 4 points and there is a maximum of 50 students.
The following code could be used to accomplish this task:

   char quizAnswers[51][5];
   int gradeArray[51]; // row 0 will be unused

   .
   .
   . quizAnswers gets values
   .
   .

   int stuIndex, probIndex, grade;
   for (stuIndex = 1; stuIndex < 51; stuIndex++)
   {
       grade = 0;
       for (probIndex = 0; probIndex < 5; probIndex++)
           if (quizAnswers[stuIndex][probIndex] == quizAnswers[0][probIndex])
               grade += 4;
       gradeArray[stuIndex] = grade;
   }


Ok, now you can work with one-dimensional and two-dimensional arrays, but the most important step to learn about arrays is how to pass them to functions. Since functions are critical for accomplishing tasks and organizing programs, it is vital to learn this key aspect of arrays. Read on for more...

Passing Arrays to Functions

An array is automatically passed by reference unless you declare the parameter as const. If you need to pass the array by value, the function heading would look similer to this:

   void displayArray ( const int arr [ ], int MAXSIZE );

When you pass an array to a function, it is also a good idea to pass the size of the array for processing purposes. If you notice in the above function heading, MAXSIZE is passed to represent the size of the array. In the declaration section of your program, you should initialize a variable to store the size of the array. The following is an example of a function that accepts an array and its size; the function displays the contents of the array to screen.

   void passValue ( int arr [ ], int MAXSIZE )
   {
           for ( int k = 0; k < MAXSIZE; k++)
                       cout << arr[k] << endl;

   } // end passValue ( )


The following is an example of a function that will find and return the position of the smallest value in a given array of integers:

   int positionOfMin ( int arr [ ], int size )
   {
           int positionOfMin = 0;
           int pos;

           for ( pos = 1; pos < size; pos++)
                       if ( arr[pos] < arr[positionOfMin] )
                            positionOfMin = pos;

           return positionOfMin;
   } // end positionOfMin ( )

We can now start to talk about how we may insert and delete elements in an array without causing any problems in the arrays. Let's begin by talking about insertion into an array. Read on for more...

Insertion Into an Array

You may encounter times when you need to insert an element into an array. There are two scenarios. The first is if you need to insert a value into a sorted array. The second is if you simply need to insert a value into a specified location in the array. If you need to insert a value into a specified location, you can simply insert the value into the position and then move all other following elements to the next position and increment the size of the array. If you need to insert a value into a sorted array, you must first find the location of where to put the value so the order will stay in tact. Next, you can insert the value and then move all other following elements to the next position and increment the size of the array. Both scenarios require there be room for the new element in the array. The following is an example of a function that will insert a value into an array sorted previously into ascending order:

void insertElement ( int arr [ ], int& size, int newElement )
{
   int insertPosition, k;

   insertPosition = -1;
   do
           insertPosition++;
   while ( newElement > arr[insertPosition] && insertPosition != size - 1 )

   if ( newElement <= arr[insertPosition] )
   {
           for ( k = size - 1; k >= insertPosition; k-- )
               arr[k+1] = arr[k];
           arr[insertPosition] = newElement;
   }
   else
           arr[size] = newElement;

   size++;
}// insertElement ( )


If you had to insert an element into a specified location in the array, you could easily use the for loop in the above example.. Simply designate the location to be filled as insertPosition, and the loop will take care of moving all following elements to the next position. You can then insert the element and increment the size of the array.



The following demonstrates a program that will allow the user to insert an element into a specified location of a pre-initialized array.

////////////////////////////////////////// Compiled Using Dev-C++ Compiler ///////////////////////////////////////////

#include <iostream.h>
#include <stdlib.h>

void insertPosition(int arr[], int& size, int element, int position);

int main()
{
     int nums[10] = { 34, 12, 89, 22, 21, 45, 55, 93, 27, 76 };
     int size = 10;
     int element;
     int position;

     for (int k = 0; k < size; k++)
           cout << nums[k] << "  ";

     do
     {
           cout << endl << endl << "Enter the position in the array for insertion (0 - 9): ";
           cin >> position;
     } while (position < 0 || position > 9);

     cout << "Enter the value to be inserted into position [" << position
           << "] of the array: ";
     cin >> element;

     insertPosition(nums, size, element, position);

     cout << endl << endl;
     for (int k = 0; k < size; k++)
           cout << nums[k] << "  ";

     cout << endl << endl << endl;

     system("PAUSE");
     return 0;
}// end main()

void insertPosition(int arr[], int& size, int element, int position)
{
     for (int k = size - 1; k >= position; k--)
           arr[k+1] = arr[k];
     arr[position] = element;

     size++;
}// end insertPosition()

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


We have now covered how to insert an element into an array, but what if you need to delete an element from an array? Before moving on the next section, try to devise a function to handle such a situation. After a couple of minutes, read on to learn how to delete an element from an array...

Deletion From an Array

As with inserting an element into an array, there are two scenarios you could face when dealing with deleting an element from an array. The first scenario is if you know the exact location of the value to be deleted. The second is if you know the value to be deleted but have no idea of its location in the array. If you know the exact location of the value to be deleted, you can create a for loop that will shift all of the elements following the location of the value to be deleted to the left one location. You also have to decrement the size since you erased one its elements. If you know the value to be deleted, you must first find the position of the value in the array. After you find the position, you can then perform the same operation as the first scenario. The following is an example of a function that will delete a value in an array given its position in the array:

void deleteElement ( int arr [ ], int& size, int position )
{
   int k;

   if ( position >= size )
           cout << "Error! You are attempting to delete an element beyond the size of the array.";
   else
   {
           for ( k = position; k < size - 1; k++ )
               arr[k] = arr[k+1];
           --size;
   }
}// end deleteElement ( )


The following is an example of segment of code that will find the position of a value in a given array:

   for (int k = 0; k < size; k++ )
           if ( arr[k] == value )
               position = k;



The following demonstrates a program that deletes a value from an array prevously initialized.

/////////////////////////////////////////////// Compiled with Dev-C++ Compiler //////////////////////////////////////

#include
#include

void deleteElement(int arr[], int& size, int position);

int main()
{
     int nums[10] = { 13, 22, 53, 14, 35, 66, 27, 98, 29, 10 };
     int size = 10;
     int position;

     for (int k = 0; k < size; k++)
           cout << nums[k] << "  ";

     cout << endl << endl;
     cout << "Enter the position of the value to be deleted (0 - 9): ";
     cin >> position;

     deleteElement(nums, size, position);

     cout << endl << endl;
     for (int k = 0; k < size; k++)
           cout << nums[k] << "  ";

     cout << endl << endl << endl;

     system("PAUSE");
     return 0;
}

void deleteElement(int arr[], int& size, int position)
{
     int k;

     if (position >= size)
     {     cout << "Error: attempting to delete beyone the size of the array!" << endl;
           system("PAUSE");
           exit(1);
     }
     else
     {
           for (k = position; k < size - 1; k++)
                 arr[k] = arr[k+1];

           --size;
     }
}// end deleteElement()

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Ok, so now you know how to work with 1D and 2D arrays, pass them to functions, and insert and delete elements. Can you think of anything else you may need to know concerning arrays? What if you need to search for an element in the array. Can you write code to handle this situation? Read on for more...

Searching Arrays

You may face times when you need to search through an entire array to look for specific data, whether it be integer values, floating point values, or characters. Maybe you need to delete the data or you need to move it to another position in the array. Whatever the case may be, I will introduce you to two standard methods for searching arrays: a linear search, and a binary search. Let's start with the linear search.

Linear Search
The definition of linear is of, or relating to a line; from a programmer's perspective, a linear search will evaluate every element in the array to see if it matches the target value, which is the element you are searching for. You can think of the array as a line connected by many dots (rows), and the linear search evaluates each dot (row) in the line. Linear searches start by examining the value in position 0 of the array; if this is the "target" item, return 0; otherwise, move up to position 1 and repeat the process (return 1 if the target is equal to the value in position 1; if not, move on to position 2). Repeat this process until the target is found (return the position it was found in) or the end of the array is reached without finding the target. If the target was not found, you can simply return -1 to indicate a failure.

The following is a function that can be used as a linear search for an array of integers:

   int linearSearch(int arr[], int size, int target)
   {
           int position;
           for (position = 0; position < size; position++)
               if (arr[position] == target)
                   return position;
           return -1;
   }// end linearSearch()


When this function is called, one of two values will be returned: the target's position in the array or -1, which indicates failure. For efficiency sake, for an array of size N, the worst possible case would be N "attempts" while searching the array. The average case is (n+1)/2 "attempts".

Binary Search
It is important to note that for a binary search to work, the array must be sorted into ascending or descending order. This will make sense in a minute. The definition of binary is something made of two components or parts. For our sake, it means the array will be divided in half each cycle through the search. It roughly divides the array in half after each attempt to find the target. Binary searches begin by "checking" the middle element in the array; if this matches the target, the position of the element will be returned. If not, it will restrict the next attempt to either the upper or lower half of the (current) array. This is continued until the target is found (return position) or every position has been logically checked with no target value found (failure). A failure is determined by checking for a "low" position that is greater than the "high" position.

The following function can be used to search an array of integers that was previously sorted into ascending order:

   int binarySearch(int arr[], int size, int target)
   {
       int middlePosition, middleValue;
       int low = 0, high = size - 1;

       while (low <= high)
       {
           middlePosition = (low + high) / 2;
           middleValue = arr[middlePosition];
           if (target == middleValue)
               return middlePosition;
           else if (target < middleValue)
               high = middlePosition - 1;
           else
               low = middlePosition + 1;
       }
       return -1;
   }// end binarySearch()


Now, you have the ability to search arrays, but maybe you would like to shuffle the contents of an array. Read on for more...

Shuffling Array Elements

Writing code to shuffle the contents of an array can take some imagination. Basically, you have two options. One way would be to choose a number at random (which is in the proper range) and place it in the array in position 0; repeat this process and place the next random number in position 1, 2, 3, to size (size of the array) - 1. This option could work, but you must avoid duplicating values when choosing the numbers at random (very inefficient). The second way would be to randomly choose a position (0 to size - 1) and swap the value in that position with the value in the "last" position (size - 1). Next, randomly select another position (0 to size - 2) and swap its value with the one in the next-to-last position. Repeat this process until position 1 is reached. Essentially, this type of shuffle would send the current randomly chosen position value to the end of the array, and then restrict the next shuffle so the previous "locked in" values would not be manipulated. Obviously, the second option is more efficient and would not duplicate values during the shuffle since the values themselves are not being randomly chosen, but rather the positions in the array are being randomly chosen.

The following is code that would shuffle the contents of an integer array:

NOTE: you must use a randomize( ) function to generate random numbers; the specific functions to handle this are different for every compiler; my code is written to work for Dev C++'s compiler [rand( ) is their randomize function].

   void shuffleElements(int theArr[], int size)
   {
       int temporary, randomNum, last;

       for (last = size; last > 1; last--)
       {
           randomNum = rand( ) % last;
           temporary = theArr[randomNum];
           theArr[randomNum] = theArr[last - 1]
           theArr[last - 1] = temporary;
       }
   }// end shuffleElements( )


If you wanted to write code to shuffle the contents of an array to mimic the shuffling of cards in a deck where you could shuffle the cards back into their previous positions as you shuffle, you could use the following piece of code:

   void shuffleCards(int arrDeck[])
   {
       for (int card = 0; card < 52; card++)
       {
           int randNum, temporary;
           randNum = rand( ) % 52;
           temporary = arrDeck[card];
           arrDeck[card] = arrDeck[randNum];
           arrDeck[randNum] = temporary;
       }
   }// end shuffleCards( )


Shuffling the elements in an array is necessary for generating latin squares. Read on for more...

Generating Latin Squares

Two dimensional arrays are necessary for applications involving the generation of Latin squares. A Latin square of order N is an N x N matrix in which each row and col contains each of the values 1, 2, 3, ..., N, exactly one time. The following...

   5  1  2  3  4
   2  3  4  5  1
   4  5  1  2  3
   1  2  3  4  5
   3  4  5  1  2

is an example of a Latin square of order 5. The following Latin square could be generated by the algorithm I depict later:

   5  1  2  3  4
   4  5  1  2  3
   3  4  5  1  2
   2  3  4  5  1
   1  2  3  4  5

Why use Latin squares? Well, they are actually commonly used in the design of statistical experiments. For example, if we wanted to test the effects of 5 different drugs on mice, and there are 5 different groups of mice, each with 5 different sizes, then we could use a latin square of order 5. Each drug will be tested on each group and each size. It turns out that it takes 25 tests to accomplish this; if you wanted to test every drug on each group in each size, it would require 125 tests.

To generate a Latin square of order N, first generate a random permutation of the digits 1 through N. You could generate this permutation by using the "shuffle" function in earlier articles, see [Shuffling Array Elements]. This ordering turns out to be the 1st row of the Latin square. You then take (1st digit - 1) of the permutation to be the index of the next digit to be placed in the matrix. Place this digit in the other rows in the order givin by the permutation (always subtracting one to get the position). Next, rotate the permutation to the left 1 position and repeat this process. You must always go back to the original permutation, which is the first row of the Latin square, to find the digit to be placed throughout the Latin square.

In other words, the (1st digit - 1) of the new permuation gives the index; that position in the original permutation gives the number to be placed; the new permutation gives the ordering; repeat this process until all of the rows are filled.

For example, suppose we want to generate a Latin square of order 6, and we used the "shuffle" function mentioned earlier to generate the random sequence:

   6  3  1  4  2  5

The first digit in this permutation is 6. The index of the value we want to place in the Latin square is (6-1) = 5. Position 5 in the original permutation contains a value of 5. This 5 is the value to be placed in the Latin square in the following manner based on the new permutation:

(6-1) = position 5 in row 0
(3-1) = position 2 in row 1
(1-1) = position 0 in row 2
(4-1) = position 3 in row 3
(2-1) = position 1 in row 4
(5-1) = position 4 in row 5

We then need to rotate the permutation one place to the left. We then end up with...

   3  1  4  2  5  6

The first digit in this new permuation is 3. The index of the value we want to place in the Latin square is (3-1) = 2. Position 2 in the original permutation contains a value of 1. This 1 is the value to be placed in the Latin square in the following manner based on the new permutation:

(3-1) = position 2 in row 0
(1-1) = position 0 in row 1
(4-1) = position 3 in row 2
(2-1) = position 1 in row 3
(5-1) = position 4 in row 4
(6-1) = position 5 in row 5

The new permutation would then be rotated one place to the left and the process would be repeated until all positions in the Latin square are filled. Our completed Latin square would look like this:

   6  3  1  4  2  5
   1  4  5  6  3  2
   5  6  2  1  4  3
   2  1  3  5  6  4
   3  5  4  2  1  6
   4  2  6  3  5  1

You may think that writing code to generate a Latin square would be quite tricky, but once you see the code, you will realize that it is really not that difficult. The following code will produce and display a Latin square of order 5 (code written to be compatitable with DEV C++ compiler).



///////////////////////////////////////////////////////////////////////////////////////////////////

#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip.h>

typedef int tRow[10];
typedef tRow tLatinSquare[10];

int getSize();
void shuffle(int arr[], int size);
void rotate(tRow list, int size);

int main()
{
     tRow sequence, randomList;
     tLatinSquare square;
     int position, value, i, j, size;
     char ch;

     srand((unsigned)time(NULL));
     size = getSize();
     while (size != 0)
     {
           shuffle(randomList, size);
           for (i = 0; i < size; i++)
                 sequence[i] = randomList[i];

           for (i = 0; i < size; i++)
           {
                 position = sequence[0];
                 value = randomList[position - 1];

                 for (j = 0; j < size; j++)
                       square[j][sequence[j] - 1] = value;

                 rotate(sequence, size);
           }

           cout << endl;
           cout << "A Latin Square of Order " << size << " is: " << endl << endl;

           for (i = 0; i < size; i++)
           {
                 for (j = 0; j < size; j++)
                       cout << setw(5) << square[i][j];
                 cout << endl;
           }

           cout << endl << "Press any key to enter a new desired size..."
                 << endl << endl;
           system("PAUSE");
           cout << endl << endl;
           size = getSize();
     }

     cout << endl << endl;

     system("PAUSE");
     return 0;
}// end main()

int getSize()
{
     int size;

     do
     {
           cout << "Enter the desired order of the Latin Square (3 - 10) or 0 to stop: ";
           cin >> size;
     } while ((size < 3 || size > 10) && size != 0);

     return size;
}// end getSize()

void shuffle(int arr[], int size)
{
     int i, temp, ran, last;

     for (i = 0; i < size; i++)
           arr[i] = i + 1;

     for (last = size; last > 1; last--)
     {
           ran = rand() % last;
           temp = arr[ran];
           arr[ran] = arr[last - 1];
           arr[last - 1] = temp;
     }
}// end shuffle()

void rotate(tRow list, int size)
{
     int temp, i;

     temp = list[0];
     for (i = 0; i < size - 1; i++)
           list[i] = list[i+1];
     list[size - 1] = temp;
}// end rotate()

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


We are now starting to explore more interesting and challenging information. Well, now that we have touch-based with arrays, we can now talk about how to sort arrays. Yes, there will be times when you will have an array that contains thousands of unsorted integers or other elements. Your job will be to sort this entire array and either put the integers in ascending or descending order. Stop and think for a minute about how you might devise a function to handle this type of situation. Ok, you can stop pondering. Lucky for you, I have already came up with a couple of ways ( standard techniques ) to sort arrays, and I have decided to share them with you. When you see the code, you will wonder why you couldn't develop it. Read on for more about the first sort I will cover: the selection sort...

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If Java had true garbage collection, most programs would delete themselves upon execution.” - Robert Sewell