Random_n in C Language

Source: Internet
Author: User

 

Some data is always input manually during algorithm sorting, which is somewhat inconvenient and acceptable for small data input. However, when the data volume reaches K level, it becomes complex. We also need to ensure that the input data is not too many duplicates or does not repeat, which is a test of our memory. All I write a program that generates N unordered integers. This program can generate N numbers, which are different from 0 to N.

 

The Code is as follows:

 

# Include <stdio. h>

# Include <stdlib. h>

# Include <time. h>

 

# Define MAX_NUM 10 // data volume to be generated

 

Void random_n (int a [], int n); declare the random_n Function

 

Int main ()

{

Int a [MAX_NUM], I = 0, j = 0;

While (j <MAX_NUM)

{

A [j] =-1; // initialization, which is very important. a large heel header was previously planted during initialization.

J ++;

}

Random_n (a, MAX_NUM );

While (I <MAX_NUM)

{

Printf ("% d \ t", a [I]);

I ++;

}

Printf ("\ n ");

Return 0;

}

Void random_n (int a [], int n)

{

Int temp = 0, j = 0, count = 0, I = 0;

Srand (time (0 ));

While (count <n)

{

Printf ("\ nStart! \ N ");

Temp = rand () % n;

Printf ("\ ncount = % d, temp = % d", count, temp );

For (j = 0; j <count; j ++)

{

If (a [j] = temp)

{

Printf ("Find! \ N ");

I = 1;

Break;

}

Else

{

I = 0; // mark

}

}

If (j = count & I = 0) // The comparison is complete and the same

{

Printf ("\ nNOT Find! \ N ");

A [count] = temp;

Count ++;

}

}

 

}

Running result: zookeeper

 

After adding this small function, we can directly call this function when entering algorithm data. First, declare an array containing MAX_NUM elements, and then pass the parameter to the random_n function. The worst running condition of the algorithm is O (N ^ 2), and the best running condition is O (N ).

 

 

This algorithm is not very efficient. I will introduce you to a more efficient method for generating unordered numbers.

From Mingyue Tianya

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.