- duanjiajun's blog
一维数组
- 2023-8-12 17:09:39 @
#include <bits/stdc++.h>
using namespace std;
//int arr[100]; // 全局变量,自动置零
//int sum; // 全局变量,自动置零
int main() {
// 数组
// 1. 一维数组的操作
// (1) 使用 1 号元素
int n;
cin >> n;
const int MAXSIZE = 100; // 常量
int arr[MAXSIZE]; // 数组的定义
memset(arr, 0, sizeof(arr)); // 批量置零
// 一维数组 批量读取
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
sort(arr + 1, arr + 1 + n); // 排序
// 一维数组 批量输出
for (int i = 1; i <= n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// (2) 使用 0 号 元素
int n;
cin >> n;
const int MAXSIZE = 100; // 常量
int arr[MAXSIZE]; // 数组的定义
memset(arr, 0, sizeof(arr)); // 批量置零
// 一维数组 批量读取
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
sort(arr, arr + n); // 排序
// 一维数组 批量输出
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
一维数组排序
#include <bits/stdc++.h>
using namespace std;
int main() {
// 3、一维数组的排序
int n;
cin >> n;
const int MAXSIZE = 100 + 1;
int arr[MAXSIZE];
memset(arr, 0, sizeof(arr));
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
// (1) 冒泡排序
for (int i = 1; i <= n; i++) {
for (int j = n; j > i; j--) {
if (arr[j] < arr[j - 1]) { // < 升序,> 降序
swap(arr[j], arr[j - 1]);
}
}
}
// (2) 冒泡排序(优化,用于接近完成的序列)
bool exchange;
for (int i = 1; i <= n; i++) {
exchange = false;
for (int j = n; j > i; j--) {
if (arr[j] < arr[j - 1]) { // < 升序,> 降序
swap(arr[j], arr[j - 1]);
cout << "swap : " << arr[j] << " <-> " << arr[j - 1] << endl;
exchange = true;
}
}
if (!exchange) break;
}
// (3) 选择排序
for (int i = 1; i < n; i++) {
for (int j = i; j <= n; j++) {
if (arr[i] > arr[j]) { // 确定擂主
swap(arr[i], arr[j]);
}
}
}
// (3) 插入排序
for (int i = 1; i <= n; i++) {
for (int j = i; j > 1; j--) {
if (arr[j] < arr[j - 1]) {
swap(arr[j], arr[j - 1]);
}
}
}
for (int i = 1; i <= n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// (4) 计数排序
int n;
cin >> n;
const int MAXSIZE = 100 + 1;
int arr[MAXSIZE];
memset(arr, 0, sizeof(arr));
int num;
for (int i = 1; i <= n; i++) {
cin >> num;
arr[num]++;
}
// 去重输出
for (int i = 1; i <= MAXSIZE; i++) {
if (arr[i] > 0) {
cout << i << " ";
}
}
cout << endl;
// 重复元素输出
for (int i = 1; i <= MAXSIZE; i++) {
while (arr[i] > 0) {
cout << i << " ";
arr[i]--;
}
}
cout << endl;
// (5) sort 排序
int n;
cin >> n;
const int MAXSIZE = 100 + 1;
int arr[MAXSIZE];
memset(arr, 0, sizeof(arr));
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
sort(arr + 1, arr + 1 + n); // 升序排序
sort(arr + 1, arr + 1 + n, greater<int>()); // 降序排序
for (int i = 1; i <= n; i++) {
cout << arr[i] << " ";
}
cout << endl;
int cnt = unique(arr + 1, arr + 1 + n) - (arr + 1); // 去重 , 并返回去重后的数量
for (int i = 1; i <= cnt; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}