Write a program that asks the user to enter 1000 integers to be stored in an arr
ID: 3835268 • Letter: W
Question
Write a program that asks the user to enter 1000 integers to be stored in an array called "numbers". Since the same integer might occur (exist) in the array multiple times, your program needs to fill a second array, called "Isolate" that contains all the integers from the first array but NOT REPAPTED (every integer will exist only once). Finally, your program will print the integers of the second array sorted by occurrence (occurrence is: the number of times the element is repeated in the first array). You can use any sorting algorithm you want. (You must use at least repeated one function in your program)Explanation / Answer
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void findCounts(int *arr, int n)
{
// Traverse all array elements
int i = 0;
while (i<n)
{
// If this element is already processed,
// then nothing to do
if (arr[i] <= 0)
{
i++;
continue;
}
// Find index corresponding to this element
// For example, index for 5 is 4
int elementIndex = arr[i]-1;
// If the elementIndex has an element that is not
// processed yet, then first store that element
// to arr[i] so that we don't loose anything.
if (arr[elementIndex] > 0)
{
arr[i] = arr[elementIndex];
// After storing arr[elementIndex], change it
// to store initial count of 'arr[i]'
arr[elementIndex] = -1;
}
else
{
// If this is NOT first occurrence of arr[i],
// then increment its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means the element
// 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
for(int i=0;i<n-1;i++){
printf(" Below are counts of all elements ");
for (int i=n-1; i>=0; i--){
if(arr[i]!=0)
printf("%d -> %d ", i+1,abs(arr[i]));
}
}
};
int main()
{
int numbers[1000], Isolate[1000];
cout<<" Enter 1000 integers : ";
for(int i=0;i<1000;i++)
cin>>numbers[i];
findCounts(numbers,1000);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.