在 C++ 中根据另一个数组定义的顺序对数组进行排序
在本节中,我们将看到另一个排序问题。假设我们有两个数组 A1 和 A2。我们必须对 A1 进行排序,以便元素之间的相对顺序与 A2 中的顺序相同。如果 A2 中不存在某些元素,则它们将附加在已排序元素之后。假设 A1 和 A2 如下所示:
A1 = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8}
A2 = {2, 1, 8, 3}排序后 A1 将如下所示:
A1 = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}为了解决这个问题,我们将创建我们自己的自定义比较方法。该方法将比较并放置数组中的元素。比较逻辑如下所示:
- 如果 num1 和 num2 都在 A2 中,则在 A2 中索引较低的数字将被视为小于另一个数字
- 如果 num1 或 num2 存在于 A2 中,则该数字将被视为小于另一个不在 A2 中的数字。
- 如果两者都不在 A2 中,则使用自然排序。
算法
compare(num1, num2): Begin if both num1 and num2 are present in A2, then return index of num1 – index of num2 else if num1 is not in A2, then return -1 else if num2 is not in A1, then return 1 else num1 – num2 End
示例
#include<iostream>
#include<algorithm>
using namespace std;
int size = 5;
int A2[5]; //global A2 will be used in compare function
int search_index(int key){
int index = 0;
for(int i = 0; i < size; i++){
if(A2[i] == key)
return i;
}
return -1;
}
int compare(const void *num1, const void *num2){
int index1 = search_index(*(int*)num1);
int index2 = search_index(*(int*)num2);
if (index1 != -1 && index2 != -1)
return index1 - index2;
else if (index1 != -1)
return -1;
else if (index2 != -1)
return 1;
else
return (*(int*)num1 - *(int*)num2);
}
main(){
int data[] = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8};
int n = sizeof(data)/sizeof(data[0]);
int a2[] = {2, 1, 8, 3};
int n2 = sizeof(a2)/sizeof(a2[0]);
for(int i = 0; i<n2; i++){
A2[i] = a2[i];
}
qsort(data, n, sizeof(int), compare);
for(int i = 0; i<n; i++){
cout << data[i] << " ";
}
}输出
2 2 1 1 8 8 3 5 6 7 9
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP