c - 在c中根据另一个数组按升序对一个数组进行排序

标签 c arrays

我想按升序对一个数组进行排序,但应检查其他数组的值。

例如: 我有两个数组 diff[] 和 arr[]
我想根据 diff[] 值对 arr[] 进行排序。
这可能吗?

我对简单的排序算法进行了更改。但并没有成功。

代码:

for (i = 0; i < n; ++i)
    {
        for (j = i + 1; j < n; ++j)
        {
            if (diff[i] > diff[j])
            {
                a =  arr[i];
                arr[i] = arr[j];
                arr[j] = a;
            }
        }
    }

最佳答案

根据您提供的示例:-

arr[]={ 17,14,14,12,11,11,9,5,4,2}
diff[]={ 12,9,9,7,6,6,4,0,1,3} 
sorted arr[]={,5 ,4 ,2 ,9 ,11......}

Algorithm:-

use can use selection sort with some modification.
1. find index of 1st minimum in diff[].
---(diff[7]=0 therefore index=7)
2.swap arr[] with arr[i] and arr[index_of_minimum]. (initially i=0)
---(swap arr[0] & arr[7]) so, new arr[]={5,14,14,12,11,11,9,17,4,2}
3.1st element is sorted so i++.
4.find index of 2nd minimum in diff[] and repeat till size of diff[].

关于c - 在c中根据另一个数组按升序对一个数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29821086/

相关文章:

java - 使用 Jaxb 从 xsd 生成 java 数组而不是 Collection 类型

c - 'main' 函数是否属于 C 中的函数定义?

c - 如何从一行接受一定量的输入

c - 在c中从UDP服务器上的Matlab Simulink接收二进制64位 float

python - 根据顺序将数组拆分为同等权重的 block

c - 删除结构体的设置间隔

c - 如何在不覆盖c中的struct的情况下附加元素

c - 在c中,什么是int(*)[]?

uitableview - 如何从 NSMutableArray 在 UITableViewCell 中显示图像?

ios - 产生错误的空数组