21xrx.com
2024-03-28 17:07:12 Thursday
登录
文章检索 我的文章 写文章
C中的选择排序
2021-07-07 07:24:52 深夜i     --     --
C

C中的选择排序以升序对数组的数字进行排序。 稍加修改,它按降序排列数字。

选择排序算法(升序)

 

  1. 找到数组中的最小元素并将其与第一个位置的元素交换。
  2. 再次在剩余的数组 [2, n] 中找到最小元素并将其与第 2 个位置的元素交换,现在我们在正确的位置有两个元素。
  3. 我们必须这样做 n-1 次才能对数组进行排序。

 

C中的选择排序程序

#include <stdio.h>


int main()
{
  int array[100], n, c, d, position, t;

  printf("Enter number of elements\n");
  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  for (c = 0; c < (n - 1); c++) // finding minimum element (n-1) times
  {
    position = c;

    for (d = c + 1; d < n; d++)
    {
      if (array[position] > array[d])
        position = d;
    }
    if (position != c)
    {
      t = array[c];
      array[c] = array[position];
      array[position] = t;
    }
  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c < n; c++)
    printf("%d\n", array[c]);

  return 0;
}

 

程序输出:

下载选择排序程序。

  
  
下一篇: C中的矩阵加法

评论区

{{item['qq_nickname']}}
()
回复
回复