J
J
Jolek2020-11-23 19:46:08
C++ / C#
Jolek, 2020-11-23 19:46:08

How to sort an array with random values?

I can’t figure out how to correctly write the code for sorting an array using the bubble method in C language, and how can I then display the sorted array on the screen

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

int main(){
  system("chcp 1251");
  system("cls");
  system("title Pr101");
  system("Color F0");
  int i, a, n, j, b, d;
  int x[i];
  int rand(void);
  printf(" Количество элементов массива: ");
  scanf("%d", &n);
  if(n <= 0){
    printf("Введите целое положительно число!");
    return 0;
  }
  printf("\n Массив x \n");
  for(d=0; d < n; d++)
  x[i] = rand();
    printf("%d", x[i]);
    for(j=1; j<=n-1; j++){
        for(i=0; i<=n-1-j; i++){
             if(x[i]>x[i+1]){
             	b = x[i];
             	x[i] = x[i+1];
             	x[i+1] = b;
       }
  }
}
  return 0;
}

Please tell me where am I wrong

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2020-11-23
@res2001

Sorting doesn't work.
1. here:

int i, a, n, j, b, d;
int x[i];

What size do you think array x will be after this declaration?
2. in the random array generation cycle:
for(d=0; d < n; d++)
  x[i] = rand();

Which array element are you assigning a value to?
3. What element is displayed? How many elements will be displayed? And this is generally some kind of holiday:printf("%d", x[i]);
system("chcp 1251");
  system("cls");
  system("title Pr101");
  system("Color F0");

But there is no mistake :)

W
Wataru, 2020-11-23
@wataru

for(d=0; d < n; d++)
  x[i] = rand();
 printf("%d", x[i]);

Loop through d and assign to x[i]. There are no parentheses yet, printf will be executed only once after the loop.
If you don't output the array after sorting, how are you even going to know that your program is working?
There are no errors in sorting itself (loops on i and j).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question