Create a 10 integer array and fill it with random integers between 1and 100. The
ID: 651295 • Letter: C
Question
Create a 10 integer array and fill it with random integers between
1and 100. The using the exchange sort, sort it so that the lowest values are first in the
array and larger numbers
are last. Here is an example of a run
array before sorting: 83 90 46 93 5 22 30 2 70 6
array after sorting: 2 5 6 22 30 46 70 83 90 93
//Exchange Sort Function for Descending Order
void ExchangeSort(apvector <int> &num)
{
int i, j;
int temp; // holding variable
int numLength = num.length( );
for (i=0; i< (numLength -1); i++) // element to be compared
{
for(j = (i+1); j < numLength; j++) // rest of the elements
{
if (num[i] < num[j]) // descending order
{
temp= num[i]; // swap
num[i] = num[j];
num[j] = temp;
}
}
}
return;
}
The exchange sort starts with the first element in an array and then compares it with each
item in the array in order. If the elements are out of order, they are swapped. Once every
element is checked, the sort moves to the second element and compares it with all
elements except for the first.
Explanation / Answer
We can fill an array in java, with random numbers between 1 and 100, in an array of size 10, we can use the logic as follows:
int num[10]=0;
for (int i = 1 ; i < 100 ; i++)
{
num[i] = int Math.random() * 100 ;
}
//Exchange Sort Function for Ascending Order
void ExchangeSort(apvector <int> &num)
{
int i, j;
int temp; // holding variable
int numLength = num.length( );
for (i=0; i< (numLength -1); i++) // element to be compared
{
for(j = (i+1); j < numLength; j++) // rest of the elements
{
if (num[i] > num[j]) // Ascending order
{
temp= num[i]; // swap
num[i] = num[j];
num[j] = temp;
}
}
}
return;
}