【问题标题】:Sorting algorithm with 10 elements具有 10 个元素的排序算法
【发布时间】:2015-07-26 21:42:36
【问题描述】:

我必须编写一个程序,要求用户输入一个由10 元素组成的数组,其数字从09

然后将数组发送给函数。该函数将对数组中的每个数字进行如下排序:

我不知道如何重新定位数字。

【问题讨论】:

  • 你是说你不知道如何交换数字,或者你不明白问题在问什么?问题是要求您获取数组中每个位置的索引并匹配一个值。第一个索引为 0,但数组中没有匹配的值,所以在索引 0 标记的元素中放置一个值 0。下一个元素是 1,所以尝试在数组中找到一个值 1,如果你找到它,将其放置在索引为 1 的元素处,否则,将其放置在 0 处。下一个索引是 2 等,以此类推。像这样遍历整个数组。
  • 该功能不仅仅涉及排序。要在数组上执行其他一组操作以获得所需的输出。 What you can do is to ask the question mentioned in that link over here and also go through stackoverflow.com/help/mcve``
  • 我明白这个问题,但我不明白如何解决这个问题。
  • 如果您不知道如何交换元素,请先阅读基本的 C 书籍。如果您不知道如何排序,一个简单的谷歌搜索将立即为您提供结果,以及 stackoverflow 上的大量排序方式
  • 欢迎来到 Stackoverflow! out被初始化为 0,for(i=0;i<10;i++){out[in[i]]=in[i];} 这个问题与排序无关。 And it is about doing homework, so it is off topic. Unless you have tried something...

标签: c arrays sorting


【解决方案1】:

这是我的实现 Joel Gregory的评论:

此函数创建一个未编辑的数组,将原始内容复制到其中,然后从第一个索引循环到最后一个索引。它将用作检查索引是否匹配的基础。

在每次迭代中,如果其中任何元素与索引号匹配,该函数就会搜索未编辑的数组。如果是,它将初始值替换为索引值。否则,分配零。以此类推,直到最后一个索引。

 void swap(int *original, int max_elements) {

      int index = 0, matcher = 0, unedited[max_elements];

      // copies original to unedited
      memcpy(unedited, original, max_elements * sizeof(int));

      for (--index; ++index < max_elements; ) {

           // searches the original array for matches with the current index
           // loops until it finds a match or it reaches the maximum number of elements
           for (matcher = 0; unedited[matcher] != index && ++matcher < max_elements;);

           // if there is match, the initial value is changed with it's index value, else zero is the new value.
           original[index] = (matcher != max_elements) ? index : 0;
      }
 }

输出:

Original: 1 1 7 8 2 8 1 6 3 2 
Sorted:   0 1 2 3 0 0 6 7 8 0 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2021-08-06
    相关资源
    最近更新 更多