需要创建2个随机数的数组,然后在C中对它们进行排序

问题描述 投票:-1回答:1

我有一点问题。我需要创建2个数组。首先,我必须对它们进行排序,然后我在main函数中按排序顺序编写它们。无论如何?我无望..我不知道如何在函数中声明数组。所以我可以从main调用sort函数。这是我的计划

int array_a()
{
int i,switchh,switching;
 int howmany = 10;
 int a[howmany];
 for (i=0;i<howmany;i++)
 {
    a[i] = rand() % 10+1;
 }
 for (i=0; i<howmany;i++)
 while(1){

    switchh=0;

  for (i=0; i<howmany-1;i++){
  if (a[i]>a[i+1]){
    int switching=a[i];
    a[i]=a[i+1];
    a[i+1]=switching;
    switchh = 1;
  } 
  }
  if(switchh==0)
  {
    break;
  }

}
}
int array_b()
{
     int i,switchh,switching;
 int howmany = 10;
 int b[howmany];
 for (i=0;i<howmany;i++)
 {
    b[i] = rand() % 10+1;
 }
 while(1){

    switchh=0;

  for (i=0; i<howmany-1;i++){
  if (b[i]>b[i+1]){
    int switching=b[i];
    b[i]=b[i+1];
    b[i+1]=switching;
    switchh = 1;
  } 
  }
  if(switchh==0)
  {
    break;
  }

}
}
main()
{
 return 0;      
}
c arrays function
1个回答
-1
投票

要编写一个sort函数声明一个像void sort(int *arr, int count)这样的函数,将数组传递给这个函数。请注意,您应该在程序开头一次调用srand()以获得更好的随机分布。例:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void sort(int arr[], int howmany)
{
    int i, switchh;
    while(1)
    {
        switchh = 0;
        for(i = 0; i < howmany - 1; i++)
        {
            if(arr[i] > arr[i + 1])
            {
                int switching = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = switching;
                switchh = 1;
            }
        }
        if(switchh == 0)
            break;
    }
}

int main(void)
{
    srand((unsigned)time(0));
    int howmany = 10;
    int arr[howmany];
    int i;
    for(i = 0; i < howmany; i++)
        arr[i] = rand() % 10 + 1;
    for(i = 0; i < howmany; i++)
        printf("%2d, ", arr[i]);
    printf("\n");
    sort(arr, howmany);
    for(i = 0; i < howmany; i++)
        printf("%2d, ", arr[i]);
    printf("\n");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.