198k views
2 votes
In this exercise, you will write some code that reads n unique (no duplicates!) non-negative integers, each one less than fifty (50). Your code will print them in sorted order without using any nested loops-- potentially very efficient! We'll walk you through this: First, assume you are given an int variable n, that contains the number of integers to read from standard input. Also assume you are given an array, named wasReadIn, of fifty (50) bool elements and initialize all the elements to false. Third, read in the n integers from the input, and each time you read an integer, use it as an index into the bool array, and assign that element to be true-- thus "marking" in the array which numbers have been read. Lastly the "punchline": write a loop that traverses the bool array: every time it finds an element that is true it prints out the element's INDEX -- which was one of the integers read in. Place all the numbers on a single line, separated by a single spaces. Note: this technique is not limited to 50 elements-- it works just as well for larger values. Thus, for example you could have an array of 1,000,000 elements (that's right-- one million!) and use it to sort numbers up to 1,000,000 in value!

1 Answer

5 votes

Answer:

// This program is written in C++

// It sorts array of n distinct elements in ascending order

// Comments are used for explanatory purpose

// Program starts here

#include <iostream>

using namespace std;

// Declare a maximum of 50

#define MAX 50

int main()

{

//The next line declares the array of 50 maximum integers

int Readln[MAX];

// The next line declares length of array

int n;

int temp;

// Prompt user to enter length of array

cout<<"Length of Array: ";

cin>>n;

//Check if length falls within range of 2 to MAX

while (n<2 || n>MAX)

{

cout<<"Array must have at least 2 elements and can't be more than "<<MAX<<endl;

}

// The next line declares an input element

int digit;

// The next loop statement accepts distinct array elements

for(int i=0; i<len;i++)

{

cout<<"Enter element ["<<i+1<<"] ";

cin>>digit;

// Check if digit is non-negative and less than 50; repeat until element is within range

while (digit<0 || n>49)

{

cout<<"Acceptable range is 0 to 49";

cin>>digit;

}

Readln[i] = digit;

}

//The next iteration sorts the array

for(i=0;i<n;i++)

{

for(int j=i+1;j<n;j++)

{

if(Readln[i]>Readln[j])

{

// Swap Elements

temp =Readln[i];

Readln[i]=arr[j];

Readln[j]=temp;

}

}

}

// The next line prints array elements

for(i=0;i<n;i++)

cout<<Readln[i]<<"\t";

cout<<endl;

return 0;

}

// End of program

User Nuffin
by
7.0k points