用另一个数组下标的形式记录一个一维数组中下标所对应的元素出现在个数,并对此一维数组进行排序。
例如:一个一维数组中的元素为:a[4] = { 2,3,2,5 };此数组为一个长度为4的数组,另一个空数组x[6]={ 0 };x[0] = 0,因为使用下标的形式记录a数组中的元素,此时x[]的下标为0,但a数组中没有0这个元素,所以x[0] = 0;类似,x[1]=0;x[2] = 2,这是因为在a数组中2这个元素出现了2次,同样可知,a[3] = 1,a[4] = 0,a[5] = 1;a数组中的所有元素遍历完,最大的元素为5,所以我们为x申请的空间大小为6,x[6]将不会被取到;
#include<iostream>
using namespace std;
void input(int *p,int n); //input the array value
void disp(int *p, int n); //input the input array value.
void search(int *p,int *x, int m, int n); //according the array's index to sreach element
void output(int *p, int index, int i); //input the new sort array.
int main()
{
int n;
int a[20], x[20];
n = 5; //total number of array
input(a,n);
disp(a,n);
search(a,x, n, 10);
}
void input(int *arr,int n)
{
int i;
cout << "input a array value:" << endl;
for (i = 0; i <n; i++)
{
cin >> *(arr + i); //arr + i 表示的是地址 并不是值;
}
}
void disp(int *arr, int n)
{
int i;
cout << "The array is:" << endl;
for (i = 0; i <n; i++)
{
cout << *(arr + i) << ' '; //arr + i 表示的是地址 并不是值;
}
cout << endl;
}
void search(int *p, int *x, int m, int n)
{
int i, j;
cout << "The new array is:" << endl;
for (i = 0; i < n; i++)
{
int index = 0;
for (j = 0; j < m; j++)
{
if (p[j] == i)
{
index++; //record the array's number of elements
}
}
output(x, index, i);
}
cout << endl;
}
void output(int *p, int index, int i)
{
int l;
int k = 0;
if (index != 0)
{
for (l = 0; l < index; l++) //according index to input new array
{
p[k] = i;
cout << p[k]<<' ';
k++;
}
}
}
例如以下:
主要是想清楚题目的过程,分析清楚之间的逻辑关系,明白自己定义的变量的含义,由于变量比较多,所以要多注意。