C + + Common Sort method, random number

Source: Internet
Author: User
Tags random seed

The research of C + + Common Sort method 2008-12-25 14:38 First, we introduce a function to calculate the time difference, which is defined in the <time.h> header file, so we only need to define 2 variables in this way, then subtract to calculate the difference.    The function begins with clock_t start = Clock (), the function ends with clock_t end = Clock (), and the time difference is: End-start but this imprecise multiple run times are different and the CPU Process about it (first summed up: The following algorithms in terms of time and space, as well as coding difficulty, as well as practical aspects, fast sorting method is the best!) Recommended! ~ But the hill sort is the most classic one, so it is recommended to first look at these 2 sorting algorithms) ranking algorithm is a basic and commonly used algorithm. Because of the large amount of processing in the actual work, the sorting algorithm has a high demand for the speed of the algorithm itself. In general, the performance of our so-called algorithm refers to the complexity of the algorithm, which is generally represented by the O method. I'll give you a detailed explanation later. For the sorting algorithm I would like to make a brief introduction to this article, but also to an outline. I will follow the complexity of the algorithm, from simple to difficult to analyze the algorithm. The first part is the simple sort algorithm, which you'll see in common is the algorithmic complexity of O (n*n) (because Word is not used, so superscript and subscript cannot be typed). The second part is the advanced sorting algorithm, the complexity of O (Log2 (N)). Here we only introduce an algorithm. There are several other algorithms that involve the concept of tree and heap, so this is not discussed here. The third part is similar to brain. The two algorithms here are not the best (or even the slowest), but the algorithm itself is rather peculiar and worth referencing (programming angle). It also allows us to recognize this problem from a different perspective. Part IV is a dessert that I give to everyone--a generic quick sort based on a template.    Because it is a template function can sort any data type (sorry, it uses some of the forum experts said). Now, let's get started: first, simple sorting algorithm because the program is relatively simple, so there is no comment. All the programs give the full running code and run through in my VC environment. Because there is no content involved in MFC and windows, there should be no problem with Borland C + + platforms. At the end of the code, the operating procedure is shown, hoping to help with the understanding. 1. Bubble method: This is the most primitive, is also known as the slowest algorithm. The origin of his name because its work looks like bubbling: #include <iostream.h> void Bubblesort (int* pDaTa,int Count) {int iTemp; for (int. i=1;i<count;i++) {for (int j=count-1;j>=i;j--) {if (PDATA[J]&LT;PDA         TA[J-1]) [Page] {iTemp = pdata[j-1];         PDATA[J-1] = Pdata[j];       PDATA[J] = iTemp; }}}} void Main () {int data[] = {10,9,8,7,6,5,4}; Bubblesort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; } reverse (worst case) First round: 10,9,8,7->10,9,7,8->10,7,9,8->7,10,9,8 (Exchange 3 times) Second round: 7,10,9,8->7,10,8,9->7,8,10,9 (swap 2 times) First round: 7,8,10,9->7,8,9,10 (Exchange 1 times) Number of cycles: 6 Exchanges: 6 times Other: first round: 8,10,7,9->8,10,7,9->8,7,10,9->7,8,10,9 (Swap 2 times) second round: 7 , 8,10,9->7,8,10,9->7,8,10,9 (Exchange 0 times) First round: 7,8,10,9->7,8,9,10 (Exchange 1 times) Cycles: 6 Exchanges: 3 times we gave the program section, and now we analyze it: here, The main part of the performance of our algorithm is the loop and exchange, obviously, the more times, the worse the performance. From the above program we can see that the number of cycles is fixed, for 1+2+...+n-1. Written as a formula is 1/2* (n-1) *n. Now notice that we give the definition of the O method: If there is a constant K and a start n0, when N>=n0, there is f (n) <=k*g (n), then f (n) = O (g (n)). (hehe, don't say not to learn maths well, for programming mathematics is very IMPORTANT!!!) Now let's look at 1/2* (n-1) *n, when K=1/2,n0=1,g (n) =n*n, 1/2* (n-1) *n<=1/2*n*n=k*g(n). So f (n) =o (g (n)) =o (n*n). So the complexity of our program loop is O (n*n). Look at the exchange again. As you can see from the table that follows the program, the loops of the two cases are the same and the exchanges are different. In fact, the exchange itself with the data source of the order degree has a great relationship, when the data in the reverse case, the number of exchanges with the same cycle (each cycle of the judgment will be exchanged), the complexity of O (n*n). When the data is in the positive order, there will be no exchange. The complexity is O (0). In the middle state when the order is disorderly. It is for this reason that we usually compare the algorithm by the number of cycles. 2. Exchange method: The procedure of Exchange is the clearest and simplest, and each time it is compared and exchanged with the elements of the current element one by one. #include <iostream.h> void Exchangesort (int* pdata,int Count) {int iTemp; for (int. i=0;i<count-1;i++) {for (i         NT j=i+1;j<count;j++) {if (pdata[j]<pdata[i]) [Page] {iTemp = pdata[i];         Pdata[i] = Pdata[j];       PDATA[J] = iTemp; }}}} void Main () {int data[] = {10,9,8,7,6,5,4}; Exchangesort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; } reverse (worst case) First round: 10,9,8,7->9,10,8,7->8,10,9,7->7,10,9,8 (Exchange 3 times) Second round: 7,10,9,8->7,9,10,8->7,8,10,9 (swap 2 times) First round: 7,8,10,9->7,8,9,10 (Exchange 1 times) Number of cycles: 6 Exchanges: 6 times Other: first round: 8,10,7,9->8,10,7,9->7,10,8,9->7,10,8,9 (Swap 1 times) second round: 7 , 10,8,9->7,8,10,9->7,8,10,9 (Exchange 1 times) First round: 7,8,10,9->7,8,9,10 (Swap1 cycles) Cycle times: 6 Exchanges: 3 times from a running table, swapping is almost as bad as bubbling. That's true. The number of cycles and bubbling is also 1/2* (n-1) *n, so the complexity of the algorithm is still O (n*n). Since we are unable to give all the information, we can only tell you that they are equally bad in exchange (slightly better in some cases, slightly worse in some cases). 3. Selection method: Now we can finally see a little hope: the choice method, this method improves a little bit of performance (in some cases) this method is similar to our artificial sorting habit: Choose the smallest and the first value exchange from the data, choose the smallest and the second exchange from the saved part, and then go on and on.   #include <iostream.h> void Selectsort (int* pdata,int Count) {int iTemp; A stored value.    int IPos; A storage subscript.     for (int i=0;i<count-1;i++) {iTemp = Pdata[i];     IPos = i;      The for (int j=i+1;j<count;j++) {if (pdata[j]<itemp)//Select Sort method is the exchange of the first element with the smallest element.         {iTemp = pdata[j];              IPos = j; The exchange assignment of the subscript.     [Page]}     } Pdata[ipos] = Pdata[i]; Pdata[i] = iTemp; }} void Main () {int data[] = {10,9,8,7,6,5,4}; Selectsort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; } reverse (worst case) First round:10,9,8,7-> (itemp=9) 10,9,8,7-> (itemp=8) 10,9,8,7-> (itemp=7) 7,9,8,10 (Swap 1 times) second round:7,9,8,10-> 7,9,8,10 (itemp=8) (itemp=8) 7,8,9,10 (Exchange 1 times) First round: 7,8,9,10(itemp=9) 7,8,9,10 (Exchange 0 times) Number of cycles: 6 Exchanges: 2 times other: First round:8,10,7,9-> (itemp=8) 8,10,7,9-> (itemp=7) 8,10,7,9-> ( itemp=7) 7,10,8,9 (Exchange 1 times) second round:7,10,8,9-> (itemp=8) 7,10,8,9-> (itemp=8) 7,8,10,9 (Exchange 1 times) First round:7,8,10,9-> (iTemp=9) 7,8,9,10 (Exchange 1 times) Cycles: 6 times exchanged: 3 times Unfortunately, the number of cycles required by the algorithm remains 1/2* (n-1) *n. So the algorithm complexity is O (n*n). We came to see his exchange. Because each outer loop produces only one interchange (only one minimum). So f (n) <=n so we have f (n) =o (n). Therefore, when the data is more chaotic, you can reduce a certain number of exchanges. 4. Insert method: The insertion method is more complex, its basic principle is to draw the card, in the front of the card to find the appropriate location to insert, and then continue to the next #include <iostream.h> void Insertsort (int* pdata,int Count)     {int iTemp; int iPos; for (int i=1;i<count;i++) {iTemp = Pdata[i];ipos = i-1;       while ((ipos>=0) && (Itemp<pdata[ipos])) {pdata[ipos+1] = Pdata[ipos];     ipos--; } pdata[ipos+1] = iTemp; }} void Main () {int data[] = {10,9,8,7,6,5,4}; Insertsort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; Reverse (worst case) First round: 10,9,8,7->9,10,8,7 (Exchange 1 times) (Loop 1 times) [Page] Second round: 9,10,8,7->8,9,10,7 (Swap 1 times) (Cycle 2 times) First round: 8,9,10,7->7,8, 9,10 (Exchange 1 times) (Cycle 3 cycles) Number of cycles: 6 Exchanges: 3 times Other: first round: 8,10,7,9->8,10,7,9 (Exchange 0 times) (Cycle 1 times) Second round: 8,10,7,9->7,8,10,9 (Exchange 1 times) (Cycle 2 times) First round: 7,8,10,9->7,8,9,10 (Exchange 1 times) (Cycle 1 cycles) Number of cycles: 4 Exchanges: 2 times the behavior analysis in the upper end actually creates an illusion, which makes us think that this algorithm is the best of the simple algorithm, but it is not, because its cycle times are not fixed, We can still use the O method. As can be seen from the above results, the number of cycles f (n) <= 1/2*n* (n-1) <=1/2*n*n. So the complexity is still O (n*n) (here is a description, in fact, if not to show the differences in these simple sorting, the number of exchanges can still be deduced). Now look at the swap, in terms of appearance, the number of exchanges is O (n) (derivation of similar selection method), but each time we want to do with the inner loop the same number of "=" operation. A normal exchange we need three times ' = ' and there's a lot more, so we're wasting time. In the end, I personally think that in the simple sorting algorithm, the choice method is the best. Second, advanced sorting algorithm: Advanced sorting algorithm We will only introduce this one, but also at present I know (I have seen the information) the fastest. Its work still looks like a binary tree. First we select an intermediate value middle program we use the middle value of the array, and then put smaller than it on the left, large on the right side (the implementation is to find from both sides, find a pair after exchange). The process is then used separately on both sides (the easiest method-recursion). 1. Quick sort: #include <iostream.h> void Run (int* pdata,int left,int right) {int i,j; int middle,itemp; i = left; j = Rig Ht Middle = pdata[(left+right)/2];          The median value of do{while ((Pdata[i]<middle) && (i<right))//From the left scan is greater than the number of values i++;     while ((Pdata[j]>middle) && (j>left))//From right scan is greater than the number of median j--; if (I&LT;=J)//found a pair of values {//Exchange iTemp = Pdata[i];       Pdata[i] = Pdata[j];       PDATA[J] = iTemp;       i++;     j--; } [Page]}while (I&LT;=J);//If both sides of the scanned subscript are staggered, stop (complete once)///When the left part has a value (left<j), recursive left half if (left<j) run (PDATA,LEFT,J); When the right part has a value (right>i), the recursive right half if (right>i) run (pdata,i,right); } void QuickSort (int* pdata,int Count) {run (pdata,0,count-1);} void Main () {int data[] = {10,9,8,7,6,5,4}; QuickSort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; Here I did not give an analysis of the behavior, because this is very simple, we directly to analyze the algorithm: first we consider the most ideal situation 1. The size of the array is a power of 2, so that the split can always be divisible by 2. Assume a K-square of 2, or K=LOG2 (n). 2. Each time we select a value that is exactly the median, then the array can be divided equally. First level recursion, loop n times, second layer cycle (N/2) ... So there is a total of n+2 (N/2) +4 (N/4) +...+n* (n/n) = N+N+N+...+N=K*N=LOG2 (n) *n so the algorithm complexity is O (log2 (n) *n) Other cases will only be worse than this situation, The worst case is that each time the selected middle is the minimum or maximum, then he will become the Exchange method (due to the use of recursion, the situation is worse), but the bad situation will only continue a process, to the next process is likely to have avoided the middle of the maximum and minimum value, because the array subscript changes, So the median value is not the maximum or minimum value. But how likely do you think this is going to happen? Oh, you don't have to worry about it at all. Practice has proved that most of the cases, fast sequencing is always the best. If you're worried about this problem, you can use heap sorting, which is a stable O (log2 (n) *n) algorithm, but usually slower than fast sorting (because the heap is being reorganized). Third, other sort 1. Two-way bubbling: the usual bubbling is one-way, and here is bidirectional, that is to do the reverse work. The code looks complicated, and it's a way of shaking back and forth. The author of this code thinks it will reduce the number of exchanges on the basis of bubbling (I don't think so, maybe I'm wrong). Anyway I think it's an interesting piece of code that's worth a look. #include <iostream.h> void Bubble2sort (int* pdata,int Count) {int iTemp; int left = 1; int right =count-1; int t; Do {//forward part for (int i=right;i>=left;i--) {if (pdata[i]<pdata[i-1]) [Page] {iTemp =         Pdata[i];         Pdata[i] = pdata[i-1];         Pdata[i-1] = iTemp;       t = i;     }} left = t+1;         Reverse part for (i=left;i<right+1;i++) {if (pdata[i]<pdata[i-1]) {iTemp = Pdata[i];         Pdata[i] = pdata[i-1];         Pdata[i-1] = iTemp;       t = i; }} right = T-1; }while (Left<=right); } void Main () {int data[] = {10,9,8,7,6,5,4}; Bubble2sort (data,7); for (int i=0;i<7;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\"; }2.shell sort this sort of is very complicated, see the program will know. First we need a descending step, here we use 9, 5, 3, 1 (the last step must be 1). It works by first sorting all content that is 9-1 elements apart, and then using the same method toThe ordering of 5-1 elements is the same as the second analogy. Basic idea: First take an integer less than n D1 as the first increment, dividing all the records of the file into D1 groups. All records that are multiples of the DL are placed in the same group (so the smaller the D value, the fewer the groupings, the more elements per group). First, the direct interpolation in each group is sorted, then the second increment d2<d1 repeats the above grouping and sorting until the increment dt=1 (DT&LT;DT-L&LT;...&LT;D2&LT;D1) is taken, that is, all records are placed in the same group for direct insert sorting. This method is essentially a grouping insertion method. (Note: It is best to have cardinality and even numbers in increments, so it can be set artificially) #include <iostream.h> int shellpass (int * array,int D)//one trip to D for hill insert sort {int Temp;int k=0 ; for (int i=d+1;i<13;i++) {if (array[i]<array[i-d]) {temp=array[i];   [Page] int j=i-d;    do {array[j+d]=array[j];    j=j-d;   k++;   }while (j>0 && temp<array[j]); Array[j+d]=temp;} k++;} return k;}                            void Shellsort (int * array)//Hill sort {int count=0;int shellcount=0;int d=12; The general increment sets the number of elements in the array, dividing by 2 to take small do{d=d/2; Shellcount=shellpass (array,d); count+=shellcount;} while (d>1); cout<<\ "Hill Sort, the number of keywords moved is: \" &LT;&LT;COUNT&LT;&LT;ENDL;} void Main () {int data[] = {10,9,8,7,6,5,4,3,2,1,-10,-1}; Shellsort (data); for (int i=0;i<12;i++) cout<<data[i]<<\ "\"; Cout<<\ "\\n\";} Algorithm Analysis 1. Selection of incremental sequences ShelThe execution time of the sort depends on the increment sequence. Common characteristics of good incremental sequences: ① The last increment must be 1;② should try to avoid the case that the values in the sequence (especially the neighboring values) are multiples of each other. A lot of experiments have been done to give a better result: when n is larger, the number of comparisons and movements is between nl.25 and 1.6n1.25. 2. The time performance of the shell sort is better than the direct insert sort of the time performance is better than the reason for direct insertion sorting: ① The comparison and number of moves required to insert a sort directly when the initial state of the file is basically ordered is low. ② when the n value is small, the difference between N and N2 is also small, that is, the best time to insert the order of the complexity O (n) and the worst time complexity of 0 (N2) is not very different. ③ in the beginning of the hill, the increment larger, more groups, the number of records in each group is small, so the direct insertion within the group is faster, and then the incremental di gradually reduced, and the number of groups gradually decreased, and the group of records gradually increased, but because already according to Di-1 as a distance arrangement, so that the file is closer to the orderly state So the new trip sort process is also faster. Therefore, the efficiency of hill sort is better than direct interpolation. 3. Stability of the hill sort is not stable. Iv. General sorting based on the template: This program I think there is no need for analysis, we can look at it. Do not understand can be asked on the forum. MyData.h file///////////////////////////////////////////////////////class CMyData {public:cmydata (int Index,char* Strdata); CMyData (); Virtual ~cmydata (); [Page]int M_iindex; int Getdatasize () {return m_idatasize;}; Const char* GetData () {return m_strdatamember;}; The operator is overloaded here: cmydata& operator = (CMyData &srcdata); BOOL Operator < (cmydata& data); BOOL operator > (cmydata& data); private:char* M_strdatamember; int m_idatasize; }; MyData.cpp articlePieces////////////////////////////////////////////////////////cmydata::cmydata (): M_iindex (0), m_iDataSize (0), m_ Strdatamember (null) {} cmydata::~cmydata () {if (M_strdatamember! = NULL) delete[] m_strdatamember; m_strdatamember = NULL; } cmydata::cmydata (int index,char* strdata): M_iindex (Index), m_idatasize (0), M_strdatamember (NULL) {m_idatasize = Strlen (strdata); M_strdatamember = new Char[m_idatasize+1]; strcpy (M_strdatamember,strdata); } cmydata& cmydata::operator = (CMyData &srcdata) {m_iindex = Srcdata.m_iindex; m_idatasize = SrcData.GetDataSize (); M_strdatamember = new Char[m_idatasize+1]; strcpy (M_strdatamember,srcdata.getdata ()); return *this; } bool Cmydata::operator < (cmydata& data) {return m_iindex<data.m_iindex;} bool Cmydata::operator > (cmydat a& data) {return m_iindex>data.m_iindex;}///////////////////////////////////////////////////////////////// Main program Section #include <iostream.h> #include \ "mydata.h\" template <class t> void run (t* pdata,int left,int right) {int i,j; T middle,itemp; i = left; [page]j = right; The following comparisons call our overloaded operator function middle = pdata[(left+right)/2];          The median value of do{while ((Pdata[i]<middle) && (i<right))//From the left scan is greater than the number of values i++;     while ((Pdata[j]>middle) && (j>left))//From right scan is greater than the number of median j--;       if (I&LT;=J)//found a pair of values {//Exchange iTemp = Pdata[i];       Pdata[i] = Pdata[j];     PDATA[J] = iTemp;       i++;     j--; }}while (I&LT;=J);//If both sides of the scanned subscript are staggered, stop (complete once)///When the left part has a value (left<j), recursive left half if (left<j) run (PDATA,LEFT,J); When the right part has a value (right>i), the recursive right half if (right>i) run (pdata,i,right);     } template <class t> void QuickSort (t* pdata,int Count) {run (pdata,0,count-1);} void Main () {CMyData data[] = { CMyData (8,\ "xulion\"), CMyData (7,\ "sanzoo\"), CMyData (6,\ "wangjun\"), CMyData (5,\ "vckbase\"), CMyData (4 , \ "Jacky2000\"), CMyData (3,\ "cwally\"), CMyData (2,\ "Vcuser\"), CMYdata (1,\ "isdong\")}; QuickSort (data,8); for (int i=0;i<8;i++) cout<<data[i].m_iindex<<\ "\" <<data[i]. GetData () <<\ "\\n\";  Cout<<\ "\\n\"; How to generate random numbers in C + + April 26, 2007 08:33 a random number seed in p.m.c++ is always confusing for beginners. As you know, there's a special Srand (N) function in C that can be easily implemented, but in C + + It's a bit more complicated. The following is the author learn a little bit of experience, I hope we can help.             (Here we still need to use the rand () function in the C standard library) function Description: int rand ();         : Returns a random integer from [0,max], where MAX is determined by the type of data you define, and requires # include <cstdlib>void srand (unsigned seed);           : Set random number seed, #include <cstdlib>time_t time (time_t *time);                       : Returns the current time, #include <ctime> application Example: 1): Srand (Times (0));                           Sets the random number seed int i = rand ()% N according to the system time; To obtain an integer of interval [0,n] to produce a random number between 1~10, the code is as follows: #include <iostream>using namespace std; #include <ctime> #include <         Cstdlib>int Main () {int t;       Srand (Time (0));       Seed T = rand ()% + 1;         Random number 1-10 cout << t << Endl; return 0;}      2): Srand (Time (0));                 Set random numbers according to system time seed float x = rand () * X/RAND_MAX;                      The probability of returning 1/x 3): Srand (Time (0));                Set random number seed vector<int>v; based on system time                      Random access to the array type, #include <vector>random_shuffle (V.begin (), V.end ()); STL algorithm Random_shuffle The order of the elements of the container class the following source code from the crafty19.3, the strongest source of open chess program. The notes are clear, needless to say. Q: 1. What does Knuth's book say? I missed the book. 2.static const unsigned long x[55], what is the reason for taking 55 random numbers here? 3. Can you tell me more about the algorithms or theories generated by random numbers, or recommend some references? [Code]/*a-bit random number generator. An implementation in C of the algorithm given Byknuth, the art of Computer Programming, Vol. 2, pp. 26-27. We use the e=32, so we had to evaluate Y (n) = y (n-24) + y (n-55) mod 2^32, which was implicitlydone by unsigned arithmetic.    */unsigned int Random32 (void) {/* random numbers from Mathematica 2.0.    Seedrandom = 1; Table[random[integer, {0, 2^32-1}] */static const unsigned long x[55] = {1410651636UL, 3012776752UL, 349747    5623UL, 2892145026UL, 1571949714UL,  3253082284UL, 3489895018UL, 387949491UL, 2597396737UL, 1981903553UL, 3160251843UL, 129444464UL, 1851443344UL, 41564 45905UL, 224604922UL, 1455067070UL, 3953493484UL, 1460937157UL, 2528362617UL, 317430674UL, 3229354360UL, 117491      133UL, 832845075UL, 1961600170UL, 1321557429UL, 747750121UL, 545747446UL, 810476036UL, 503334515UL, 4088144633UL, 2824216555UL, 3738252341UL, 3493754131UL, 3672533954UL, 29494241UL, 1180928407UL, 4213624418UL, 33062851UL, 3221315 737UL, 1145213552UL, 2957984897UL, 4078668503UL, 2262661702UL, 65478801UL, 2527208841UL, 1960622036UL, 315685891    UL, 1196037864UL, 804614524UL, 1421733266UL, 2017105031UL, 3882325900UL, 810735053UL, 384606609UL, 2393861397UL};    static int init = 1;    Static unsigned long y[55];    static int J, K;      unsigned long ul;          if (init) {int i;      init = 0;      for (i = 0; i <; i++) y[i] = X[i];      j = 24-1;    K = 55-1;    } ul = (Y[k] + = y[j]); if (--j &Lt    0) j = 55-1;    if (--k < 0) k = 55-1; return ((unsigned int) ul);} [/code] for beginners, just master 1 of the usage, a deeper level of ascension with the natural will have some understanding. (The above part comes from "The Lost Wolf") Another: one, C + + cannot use the random () function The random function is not ANSI C standard, can not be compiled under the compiler GCC,VC and so on.      You can use the RAND function under C + + to implement it. 1. The C + + standard function library provides a random number generator RAND, which returns a pseudo-random integer evenly distributed between 0-rand_max. The Rand_max must be at least 32767. The rand () function does not accept parameters and defaults to 1 as the seed (that is, the starting value). The random number generator always starts with the same seed, so the pseudo-random sequence is the same and loses its random meaning. (But this is easy for program debugging) 2, another function Srand () in C + +, you can specify a different number (unsigned integer variable) to seed. But if the seed is the same, the pseudo-random sequence is the same.       One way is to let the user enter the seed, but still not ideal. 3, the ideal is to use the number of changes, such as time to be a random number generator seed. The value of time is different every moment. So the seed is different, so the random number produced is different.  C + + random function (VC program) #include <stdio.h> #include <iostream> #include <time.h> using namespace std; #define MAX of the int main (int argc, char* argv[]) {Srand ((unsigned) time (NULL)), and the//srand () function produces a random seed starting at the current moment. should be put It takes a long time to wait for the for (int i=0;i<10;i++) Cout<<rand ()%max<<endl;//max to be the maximum value, with a random field of 0~max-1 return, in front of the for-wait loop statement 0; The usage of rand () rand () does not require arguments, it returns an arbitrary integer from 0 to the maximum random number, and the maximum random number size is usually a fixed large integer. This way, if you want to produce the 0~10 10 wholeNumber, which can be expressed as: int N = rand ()% 11;   Thus, the value of N is a random number of 0~10, if it is to produce 1~10, then it is: int N = 1 + rand ()% 11;   In summary, it can be expressed as: A + rand ()% n where a is the starting value and N is the range of integers. A + rand ()% (b-a+1) represents a random number between a~b to 0~1 decimal, you can get the 0~10 integer, and then divide by 10 to obtain a random decimal to a very bit of 10 random decimals, you need to get a random decimal to the percentile of the first 0~       100 of 10 integers, then all divided by 100, and so on. Usually rand () generates random numbers that are the same as the last time they were run, and this is intentionally designed to facilitate debugging of the program.       To produce a different random number each time, you can use the Srand (seed) function to randomize, and with different seed, you can produce different random numbers. As you may say, you can also include the time.h header file, and then use Srand (Time (0)) to randomize the random number generator using the current times, which guarantees that a different sequence of random numbers can be obtained every two runs (as long as the two runs are more than 1 seconds apart).

  

C + + Common Sort method, random number

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.