Hello! I have written a program that lets the user enter numbers and they are then sorted into ascending order. The number of times each number occurs is also displayed. I previously wrote it using a selection sort but could not get the times each number occured to display correctly. Now I have tried to write it using an insertion sort. The number occurences display correctly now, however, I can't get the list of numbers to display right. I get a bunch of random numbers and letters. If someone could help me tidy up my code I'd greatly appreciate it.
Also, I would like to display the number(s) that occur most often. Say for ex: I enter 6 3 6 3 5. Both 6 and 3 would would be displayed. How would I go about doing this? Thank you! :cheesy:
I have included my code as follows:
#include <iostream>
using namespace std;
int fill_array(int a[], int size, int& number_used);
void insertion_sort(int sample_array[], int size, int number_used);
void count_array(int sample_array[], int counter[], int number_used);
int count = 0;
int main()
{
cout << "This program sorts numbers from lowest to highest.\n";
int sample_array[100], number_used;
int counter[100] = {0};
fill_array(sample_array, 100, number_used);
count_array(sample_array, counter, number_used);
insertion_sort(sample_array, 100, number_used);
cout << "\n";
cout << "\n";
cout << "Numbers\t";
cout << "Times" << endl;
for (int index = 0; index < number_used; index++)
{
cout << sample_array << "\t";
cout << counter[index] << endl;
}
cout << endl;
cout << "\n";
cout << "You entered " << count << " numbers." << endl;
return 0;
}
int fill_array(int a[], int size, int& number_used)
{
cout << "Enter up to " << size << " nonnegative whole numbers.\n"
<< "Mark the end of the list with a negative number.\n";
int next, index = 0;
cin >> next;
while ((next >= 0) && (index < size))
{
a[index] = next;
index++;
cin >> next;
count++;
}
number_used = index;
return count;
}
void insertion_sort(int sample_array[], int size, int number_used)
{
int key, i;
for (int number_used=1; number_used<size; number_used++)
{
key=sample_array[number_used];
i=number_used-1;
while(sample_array[i]>key && i>=0)
{
sample_array[i+1]=sample_array[i];
i--;
}
sample_array[i+1]=key;
}
}
void count_array(int sample_array[], int counter[], int number_used)
{
for(int index=0; index<number_used; index++)
{
for(int index2=0; index2<number_used; index2++)
{
if (sample_array[index]==sample_array[index2])
counter[index]++;
}
}
}