簡體   English   中英

C語言中改進的qsort()函數

[英]An improved qsort() function in c

假設我們使用qsort()對一維數組進行排序,是否有一種簡單的方法可從排序后的數組元素中檢索該元素在排序之前在數組中被索引時所擁有的索引。 假設c [N]被排序為d [N],如何從整數i,j中查找出c [j] = d [i]呢? 當我說一種簡單的方法時,qsort(帶有一些附加參數)是否存儲這種信息(排序之后的索引之間的雙向射)或是否存在qsort改進的功能,可以輕松地對這種信息進行排序和檢索?

假設您使用以下結構填充初始數組:

struct IndexedInteger {
  int value;
  int index;
}

然后,您需要在循環中填充索引:

void addIndices(IndexedInteger * array, size_t num) {
  int i;
  for (i = 0; i < num; ++i) {
    array[i].index = i;
  }
}

然后,您將對數組進行排序:

int compareIndexed(const void * elem1, const void * elem2) {
  IndexedInteger * i1, *i2;
  i1 = (IndexedInteger*)elem1;
  i2 = (IndexedInteger*)elem2;
  return i1->value - i2->value;
}

void sortArray(IndexedInteger * array, size_t num) {
  qsort(array, num, sizeof(IndexedInteger), compareIndexed);
}

然后,您將使用初始索引對數組進行排序。

免責聲明:我寫得很快,可能會有錯誤。

您可以做的是創建一個struct ,該struct保留您的數據(在這種情況下為整數),同時還保留一個整數,該整數對應於數組最初位於該位置的位置的索引。 澄清,

#include <stdio.h>
#include <stdlib.h>

struct myData {
    int data;
    int orig_pos; // will hold the original position of data on your array
};

int myData_compare (const void* a, const void* b) {

    return ((struct myData*)a)->data - ((struct myData*)b)->data;
}

int main () {

    size_t N = 10; // size of your array
    struct myData* array = (struct myData*) malloc(N * sizeof(struct myData));
    for (size_t i = 0; i < N; i++) {
        array[i].data     = N - i; // array will hold 10,9,8,7,...1 in this order
        array[i].orig_pos = i;
    }
    qsort(array, N, sizeof(struct myData), &myData_compare);
    for (size_t i = 0; i < N; i++) {
        printf("\ndata: %d, orig_pos: %d", array[i].data, array[i].orig_pos);
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM