不使用std库在C中对数组索引进行排序 [英] Sort array index in C without using std library

查看:82
本文介绍了不使用std库在C中对数组索引进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个四位常数的整数数组(例如array [0] = 25,array [1] = 25,array [2 ] = 15,数组[3] = 25)。



我想排序数组索引。我的出局应该是2,0,1,3。



我无法想出合适的逻辑。请帮帮我。



任何帮助都将不胜感激。



全部谢谢。



问候,

Phillip

Hi Everybody,

I have an integer array of constant size four (e.g. array[0] = 25, array[1] = 25, array[2] = 15, array[3] = 25).

I want to sort array index. I.e my out put should be 2,0,1,3.

I am not able to think a proper logic. Please help me.

Any help will be appreciated.

Thanks All.

Regards,
Phillip

推荐答案

什么逻辑?这只是循环遍历数组并确定最低值项的问题。如果有,然后将其移动到结果列表的下一个位置。重复,直到你拥有所有元素。谷歌会为你找到更好的排序算法,但这对于这么小的数组也是如此。
What logic? It is just a question of looping through the array and identifying the lowest value item. When you have it then move it to the next position of your result list. Repeat until you have all elements. There are much better sort algorithms which Google will find for you, but this will do for such a small array.


在这样的情况下,它非常简单,因为你是排序数组;你是创建一个排序的数组(你很聪明,任何时候你都可以避免排序数组,你应该 - 这是Linqers似乎无法理解的东西)。 />


所以算法很简单:

0)迭代源数组。

0.1)找到现场在当前值的目标数组中。

0.1.1)移动目标中的现有值以便随时腾出空间。

0.2)存储当前值。



In a case like this, it's very simple because you're not sorting an array; you're creating a sorted array (very smart of you, any time you can avoid sorting an array, you should -- this is something that the Linqers just don't seem to understand).

So the algorithm is as simple as:
0) Iterate the source array.
0.1) Find the spot in the destination array for the current value.
0.1.1) Shift existing values in the destination to make room as a you go.
0.2) Store the current value.

void GetSortedIndices
( int size
, int numbers[]
, int indices[]
)
{
  int i , j ;

  for ( i = 0 ; i < size ; i++ )
  {
    for ( j = i ; ( j > 0 ) && ( numbers [ indices [ j - 1 ] ] > numbers [ i ] ) ; j-- )
      indices [ j ] = indices [ j - 1 ] ;

    indices [ j ] = i ;
  }

  return ;
}


这篇关于不使用std库在C中对数组索引进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆