1. 程式人生 > >(C++)用陣列下標形式對一維陣列進行排序

(C++)用陣列下標形式對一維陣列進行排序

用另一個數組下標的形式記錄一個一維陣列中下標所對應的元素出現在個數,並對此一維陣列進行排序。
例如:一個一維陣列中的元素為: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++; } } }

例如以下:
在這裡插入圖片描述
主要是想清楚題目的過程,分析清楚之間的邏輯關係,明白自己定義的變數的含義,由於變數比較多,所以要多注意。