排序数组数据,而无需修改内容 [英] Sorting Array Data without Modifying Content
问题描述
我试图写一个简单的程序,读取多个整数,将它们放入一个数组,然后调用它们排序按升序排列的功能。扭不过,是我想他们不改变数组的内容进行排序。是否有这样做的方法吗?
I'm trying to write a simple program that reads several integers, puts them into an array and then call a function that sorts them in ascending order. The twist though, is that I want to sort them without changing the content of the array. Is there any way of doing this?
int selection_sort(int *, int); //prototype
int selection_sort(int * num,int n)
//num is the first address of the array and n is array length
{
int min, target, i, j, temp;
for(i=0; i<n; i++)
{
min = num[i];
target = i;
for(j=i+1; j<n;j++)
{
if(num[j]<min)
{
min = num[j];
target = j;
}
}
if(target != i)
{
//My intuition tells me that here's where I need to work some magic
temp = &num[i];
&num[i] = &num[target]; //Here's what I was planning on doing
&num[target] = temp;
}
}
}
如果我删除的功能就像一个传统排序功能&符号,所以当我在主函数打印数组内容已被更改。所以我想,如果我改变了周围的地址,然后当我打印,然后原始(未排序)阵列将显示,可悲的是,编译器不允许我这样做。
If I remove the ampersands the function works like a traditional sorting function, so when I print it in the main function the array contents have been changed. So I thought that if I changed the addresses around, then when I printed it, then the original (not-sorted) array would show, sadly the compiler doesn't allow me to do this.
推荐答案
假设你有一个数据数组 A
与 N
在它的元素,你不能(能力)的变化,您可以创建一个平行排列 P
初始化,为 P [I] = =我
在0..N-1的每个元素。然后,您可以安排排序算法permutes数组 P
,使得 A [P [I]]
是 I
个的排序顺序元素。这是不是一个标准的排序操作,所以你必须写自己的排序code,但它不是一个可怕的排序很难写。
Assuming you have a data array A
with N
elements in it that you can't (afford to) change, you can create a parallel array P
initialized such that P[i] == i
for each element in 0..N-1. You can then arrange that the sorting algorithm permutes the array P
such that A[P[i]]
is the i
th element in the sorted order. It isn't a standard sort operation, so you'll have to write your own sort code, but it isn't a dreadfully difficult sort to write.
另一种选择是使用指针的平行阵列。如果 A
的元素类型的 T
(以便您有 TA [N];
作为数组的声明),那么你可以创建一个并行阵列 T * P [N];
和初始化每个元件,使得 P [I] ==&安培; A [I]
。然后,你可以使用标准的的qsort()
功能,后面的指针值合适的比较器进行排序 P
。这无疑是一个更好的解决方案,因为它利用了标准的排序code。一旦排序,你可以使用 * P [I]
访问 I
个在 A
按排序顺序,值而不必影响 A
本身都没有。
An alternative option is to use a parallel array of pointers. If the elements in A
are of type T
(so you have T A[N];
as the declaration of the array), then you could create a parallel array T *P[N];
and initialize each element such that P[i] == &A[i]
. Then you can sort P
using the standard qsort()
function and an appropriate comparator that follows the pointers to the values. This is arguably a better solution because it leverages the standard sorting code. Once it is sorted, you can use *P[i]
to access the i
th value in A
in sorted order, without having affected A
itself at all.
这篇关于排序数组数据,而无需修改内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!