Вопрос

EDIT : This is all done in C.

Let's say I have the two following arrays :

int numFields[] = {5, 1, 3, 2, 7}
char charFields[] = {'a' , 'b', 'c', 'd', 'e'}

I want to sort numFields numerically and have charFields resorted to match the new order of numFields such that :

int numFields[] = {1, 2, 3, 5, 7}
char charFields[] = {'b', 'd', 'c', 'a', 'e'}

I know that is possible to use qsort to sort numFields numerically, but is it possible to sort charFields to match the index changes of numFields? Is there a built in function or do I have to make my own implementation?

Thanks

Это было полезно?

Решение

qsort lets you specify your own compare function to specify on what criteria the array should be sorted. It lets you sort an array of any type (can be int, can be struct) as long as you know the size of the objects you're sorting. Your best bet will be to create a struct pair { int numValue; char charValue } to represent the pair. You can

  1. write a function to accept numFields and charFields and return an array of pair.
  2. write a compare function, using this question and answers for reference. Other code examples here.
  3. call qsort on your array of pairs and your comparison function
  4. write a function to transform the array of pairs back to charFields.

Другие советы

simply declare a struct array with each element holding the number as well as the letter corresponding to it. Then sort the array according to the numbers

or use qsort with a specific call back function to do what you need.

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

int numFields[] = {5, 1, 3, 2, 7};
char charFields[] = {'a' , 'b', 'c', 'd', 'e'};
// temporary arrays for sorted result   
int numFields2[5];
int charFields2[5];
// an index for sorting
int idx[] = {0, 1, 2, 3, 4};
// A cmompare function compares the numFields using the index values
int compar(const void* a,const void* b){
     return numFields[*(int*)a]-numFields[*(int*)b];
}

int main(void) {
    // sort the index values using the comapare function
    qsort(idx, 5, sizeof(int), compar);
    // use the sorted index to copy the values in the new sort order
    int i;
    for(i=0;i<5;i++){
      numFields2[i] = numFields[idx[i]];
      charFields2[i] = charFields[idx[i]];
     }
     // Copy result to original arrays
     for(i=0;i<5;i++){
        numFields[i] = numFields2[i];
        charFields[i] = charFields2[i];
     }
    return 0;
}

Here i try to devlop bubble sort program try using it.,

int temp;
char a;
for(i=0;i<no;i++)
    {
        for(j=i;j<no;j++)
        {
            if(numFields[i] > numFields[j])
            {
                temp=numFields[i];
                numFields[i]=numFields[j];
                numFields[j]=temp;


                a=charFields[i];
                charFields[i]=charFields[j];
                charFields[j]=a;
            }
        }
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top