首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在排序后将未排序的数组保留在C中

在排序后将未排序的数组保留在C中,可以通过以下步骤实现:

  1. 创建一个原始数组A和一个辅助数组B,它们的大小与待排序数组相同。
  2. 将待排序数组复制到辅助数组B中。
  3. 使用合适的排序算法(如快速排序、归并排序、插入排序等)对辅助数组B进行排序。
  4. 创建一个布尔数组C,大小与待排序数组相同,用于标记数组元素是否已排序。
  5. 遍历原始数组A和排序后的辅助数组B,比较元素并标记C数组中对应位置,如果两个元素相同则标记为已排序。
  6. 遍历布尔数组C,将未排序的元素重新放回原始数组A中,保持它们的相对顺序。

以下是一个示例代码(使用快速排序算法):

代码语言:txt
复制
#include <stdio.h>
#include <stdbool.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
  
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void retainUnsortedArray(int arr[], int size) {
    int* temp = malloc(size * sizeof(int));
    bool* sorted = malloc(size * sizeof(bool));
    
    for (int i = 0; i < size; i++) {
        temp[i] = arr[i];
        sorted[i] = false;
    }
    
    quickSort(temp, 0, size - 1);
    
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (arr[i] == temp[j]) {
                sorted[j] = true;
                break;
            }
        }
    }
    
    int index = 0;
    for (int i = 0; i < size; i++) {
        if (!sorted[i]) {
            arr[index++] = temp[i];
        }
    }
    
    free(temp);
    free(sorted);
}

int main() {
    int arr[] = {5, 2, 1, 4, 3};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    retainUnsortedArray(arr, size);
    
    printf("Unsorted array retained: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

输出结果为:Unsorted array retained: 5 2 1 4 3

该方法使用了快速排序算法对辅助数组进行排序,并通过布尔数组标记已排序的元素。然后根据布尔数组的标记,将未排序的元素重新放回原始数组中,保持它们的相对顺序。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器CVM:https://cloud.tencent.com/product/cvm
  • 云数据库CDB:https://cloud.tencent.com/product/cdb
  • 云原生容器服务TKE:https://cloud.tencent.com/product/tke
  • 腾讯云存储COS:https://cloud.tencent.com/product/cos
  • 腾讯云人工智能AI:https://cloud.tencent.com/product/ai
  • 物联网通信平台IoT Hub:https://cloud.tencent.com/product/iothub
  • 移动应用开发平台MTP:https://cloud.tencent.com/product/mtp
  • 腾讯云区块链服务BCS:https://cloud.tencent.com/product/bcs
  • 腾讯云游戏多媒体引擎MME:https://cloud.tencent.com/product/mme
  • 腾讯云音视频处理服务VOD:https://cloud.tencent.com/product/vod
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券