#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
// 快速排序的划分函数
int Partition(int a[], int low, int high) {
int pivot = a[high]; // 选择最后一个元素作为枢轴
int i = (low - 1); // 指向小于枢轴的元素的索引
for (int j = low; j <= high - 1; j++) {
if (a[j] <= pivot) {
i++;
// 交换 a[i] 和 a[j]
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
// 交换 a[i+1] 和 a[high] (即枢轴),就是将high的值交换到两个区间之间。
int temp = a[i + 1];
a[i + 1] = a[high];
a[high] = temp;
return (i + 1);
}
// 解决问题的主函数
int Solution(int a[], int n) {
int low = 0, high = n - 1;
while (low < high) {
int mid = Partition(a, low, high);
// 调整划分范围
if (mid == n / 2) {
break;
} else if (mid < n / 2) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// 计算两部分的元素和
int s1 = 0, s2 = 0;
for (int i = 0; i < n / 2; i++) {
s1 += a[i];
}
for (int i = n / 2; i < n; i++) {
s2 += a[i];
}
return s2 - s1;
}
int main() {
string filename = "实验08_快速排序及其应用-测试数据-1000个 (1).txt";
ifstream inputFile(filename);
if (!inputFile.is_open()) {
cerr << "无法打开文件: " << filename << endl;
return EXIT_FAILURE; // 使用 EXIT_FAILURE 表示异常退出 [ty-reference](1)
}
// 动态分配一个足够大的数组来存储所有数字
int *a = NULL;
int capacity = 1020; // 初始容量
a = (int *)malloc(capacity * sizeof(int));
if (a == NULL) {
perror("内存分配失败");
inputFile.close();
return EXIT_FAILURE;
}
int n = 0; // 记录实际读取的元素数量
int value;
while (inputFile >> value) { // 使用 C++ 的 >> 操作符读取整数
if (n >= capacity) {
// 如果当前数组已满,则增加容量
capacity *= 2;
void *temp = realloc(a, capacity * sizeof(int));
if (temp == NULL) {
perror("内存重新分配失败");
free(a);
inputFile.close();
return -1;
} else {
a = (int *)temp;
}
}
a[n++] = value;
}
inputFile.close(); // 关闭文件
// 创建或打开输出文件用于写入结果
ofstream outFile("output.txt"); // 使用 C++ 的文件流对象
if (!outFile.is_open()) {
cerr << "无法创建输出文件: output.txt" << endl;
return EXIT_FAILURE;
}
// 调用 Solution 函数并打印结果到控制台和文件
int result = Solution(a, n);
outFile << "最大的差值是: " << result <<endl;
// 输出两个分组的元素
outFile << "小于枢轴的元素:"<<endl;
for (int i = 0; i < n / 2; i++) {
outFile << a[i]<<endl; // 只需打印一次
}
outFile << "大于枢轴的元素:"<<endl;
for (int i = n / 2; i < n; i++) {
outFile << a[i]<<endl; // 只需打印一次
}
free(a); //动态分配的内存要free掉
outFile.close();
return 0;
}
程序设计的目的是:
在输出到txt文件的时候,出现了乱码问题。我的有效解决措施是把txt的编码修改一下:修改成ANSI就可以了。