2022A2实现对数组中的元素进行排序,void SelectSort (int a[n],int n),采用冒泡或快速排序算法按升序排列数组a中的n个元素,排序结果保存到文件 out.txt。

  1. 编程实现对数组中的元素进行排序,写一个函数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)
{
    //获取基准值,并与left交换位置
    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]);
    }
//         将排序后的结果写入文件 out.txt
    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");
    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值