- 编程实现对数组中的元素进行排序,写一个函数void SelectSort (int a[n],int n),采用冒泡或快速排序算法按升序排列数组a中的n个元素,并把排序结果保存到文件 out.txt。
3. #include <stdio.h>
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int PartSort(int* arr, int low, int high)
{
int poit = arr[low];
while (low < high)
{
while (low < high && arr[high] >= poit)
{
high--;
}
Swap(&arr[low],&arr[high]);
while (low < high && arr[low] <= poit)
{
low++;
}
Swap(&arr[low],&arr[high]);
}
arr[low] = poit;
return low;
}
void QuickSort(int* arr, int low, int high)
{
if (low < high)
{
int poit = PartSort(arr, low, high);
QuickSort(arr, low, poit-1);
QuickSort(arr, poit+1, high);
}
}
int main()
{
int arr[] = {5,6,34,415,77,7,88,242,999};
QuickSort(arr,0,8);
for(int i=0; i<9; i++)
{
printf("%d ", arr[i]);
}
FILE *outFile = fopen("out3.txt", "w");
if (outFile != NULL) {
for (int i = 0; i < 9; ++i) {
fprintf(outFile, "%d ", arr[i]);
}
fclose(outFile);
printf("排序后的结果已保存到 out3.txt 文件中\n");
} else {
printf("无法打开文件 out.txt\n");
}
}