>假设我有 3 个数组。
arr1 = {96, 100, 104, 108}
arr2 = {8, 4, 4, 16}
现在我创建第三个数组,我将在其中存储元素 =arr1[i]/arr2[i]
因此arr3 = {12, 25, 26, 9}
现在我想对arr3
进行排序.但也要按相同的顺序对arr1
和arr2
进行排序。
就像现在一样arr3 = {9, 12, 25, 26}
我也想按相同的顺序对arr1
和arr2
进行排序
arr1 = {108, 96, 100, 104} arr2 = {16, 8, 4, 4}
所以arr3[2] = 26
我可以打印/使用arr1[2] = 96 && arr2[2] = 8
.
我希望能够通过arr3
访问arr1
和arr2
元素。
不要对数组进行排序,对索引进行排序
#include <stdio.h>
#include <stdlib.h>
int arr1[] = {96, 100, 104, 108};
int arr2[] = {8, 4, 4, 16};
int arr3[] = {12, 25, 26, 9};
int delta(const void *a, const void *b) {
const int *aa = a;
const int *bb = b;
return arr3[*aa] - arr3[*bb];
}
int main(void) {
int indexes[] = {0, 1, 2, 3};
qsort(indexes, 4, sizeof (int), delta);
printf("arr1:");
for (int k = 0; k < 4; k++) {
printf(" %d", arr1[indexes[k]]);
}
printf("narr2:");
for (int k = 0; k < 4; k++) {
printf(" %d", arr2[indexes[k]]);
}
printf("n");
}
对不起全局者。
大多数(如果不是全部?(排序将使用元素交换。当您对arr3
进行排序并交换其中的元素时,只需交换其他数组的相应元素即可。
因此,当您交换例如arr3[i]
与arr3[j]
,然后也与arr1[j]
交换arr1[i]
,与arr2[j]
交换arr2[i]
。
首先,定义一个数据结构来保存这些值:
typedef struct {
int dividend, divisor, result;
} intTuple;
然后为 C 的qsort
定义一个排序函数
int compare(const intTuple *e1, const intTuple *e2){
return (e1->result > e2->result)? 1 : 0;
}
然后初始化数据,执行除法并调用qsort
:
int main() {
intTuple tuples[4] = { {96, 8}, {100, 4}, {104, 8}, {108, 16} };
for (int i = 0; i < 4; i++) {
tuples[i].result = tuples[i].dividend / tuples[i].divisor;
}
qsort(tuples, 4, sizeof(intTuple), compare);
for (int i = 0; i < 4; i++) {
printf("%d ", tuples[i].dividend);
}
}
在这里测试它。
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
// created a structure containing three elements
struct node
{
int a;
int b;
int c;
} arr[3];
// comparator function which is used to sort structure based on its one property 'c' value
bool compareTwoStudents(node aa, node bb)
{
return (aa.c < bb.c);
}
int main() {
arr[0].a=96;
arr[1].a=100;
arr[2].a=108;
arr[0].b=8;
arr[1].b=4;
arr[2].b=16;
arr[0].c=12;
arr[1].c=25;
arr[2].c=9;
// sort function of c++, takes third argument as the custom comparator function
sort(arr, arr+3, compareTwoStudents);
for(int i=0;i<3;i++)
{
cout<<arr[i].a<<" "<<arr[i].b<<" "<<arr[i].c<<"n";
}
return 0;
}