Comparison between C ++ implementation (bubble, selection, insertion, heap, Shell, fast, and merge) of common sorting algorithms and sort ()

Source: Internet
Author: User

I accidentally saw a sentence in the book, "C ++ProgramOne thing people talk about is the overall defeat of sort ().C Language", So I decided to test it in person, just to test the sorting of the other files, as a compensation that was not written at the beginning.

Test File description:

1. If an array is used in the test, when Max reaches 1000000, it will stack over, so vector is used here.

2. Random numbers are saved using a global vector. When sorted separately, the vector <int> V (orited) is directly used. This is really convenient for C ++, because some recursive calls, the number of vectors in the call process is mostly unknown. How to initialize arrays becomes a problem.

3. The names of the function for testing sorting are all separated by underscores (_), for example, select_sort ().

4. the sorting result is verified by writing files.

5. The files are compiled in win7, vs6, vs08, and GCC. In vs08, if a file is used for initial file operations, there will be errors. You can change it to stream. For example, to open or empty a file, modify it as follows:

 
File * fp = fopen ("data.txt", "WR"); ofstream FP ("data.txt ");
 
If (FP = NULL) if (FP. Fail ())

Write the corresponding two parts of the file, of course, when readingIp> temp;V. push_back (temp );

 
FP <orited [I] <"; // it is best to add a space here. Otherwise, the numbers in the file do not make sense. fprintf (FP," % d ", orited [I]); // close // fclose (FP); FP. close ();

The final Modified Standard C ++ test file is as follows:

// ================================================ ==================================================================== // Name: sort. CPP // Author: Xia // version: 1.0 // copyright: NUAA // Description: Sorting Algorithm (Bubble, select, fast, Hill, heap, merge, and algorithm Sort) // ================================================ ============================================= # include <iostream> # include <fstream> # include <algorithm> # include <vector> # include <ctime> using namespace STD; const int max = 1000; // when Max is 1 million, the array will stack overflow, so all vectorvector <int> orited; // The Global original unordered vectorvoid randnum () {// generate a random number stored in vectorofstream FP ("data.txt"); If (FP. fail () {cout <"op En data error "<Endl; exit (exit_failure);} srand (unsigned) Time (null); For (INT I = 0; I <Max; I ++) {orited. push_back (RAND (); // use a vector to save the random number FP <orited [I] <";} FP. close ();} /*************************************** * **********************************/* quick sorting */ /*************************************** * ********************************/INT partion (vector <int> & V, int low, int high) {// divides the vector and returns the pivot. Subscript int lower tkey; lower tkey = V [low]; while (low 

For sort (), the default values are listed in ascending order. to sort the values in descending order, you can add a function:

 
Bool compare (int A, int B) {return A> B; // A> B descending a <B ascending}

And called

 
Sort (V. Begin (), V. End (), compare );

You can.

Some test results are given in the main part of the program. The shell does not have much reference, so there is no column (in the original words of the book, shell sorting analysis is a complicated problem, because time is the function of the incremental sequence, which involves some mathematical issues that have not yet been solved), save the sorting results to the file for viewing. You can see the shell results, it is not as accurate as fast sorting, and the probability problem occurs.

The vc6 test results are as follows:

 

Sort ()

Quick

Bubble

Select

Merge

Shell

Heap

Insert

1 K

0

1

78

35

107

14

2

21

1 W

2

12

4883

3099

7947

1135

34

2274

10 W

26

142

410630

385299

774607

108289

267

220359

The test results in vs08 are as follows: (insert may have some errors in vs08, so they are not listed)

 

Sort ()

Quick

Bubble

Select

Merge

Shell

Heap

1 K

26

2

193

291

15

90

8

1 W

302

29

12674

8203

216

3010

57

10 W

3624

378

1.02754e + 006

804142

804142

804142

713

GCC test results:

 

Sort ()

Quick

Bubble

Select

Merge

Shell

Heap

Insert

1 K

0

0

9

3

1

2

1

2

1 W

2

3

725

452

81

170

4

294

10 W

29

27

55812

34269

4390

16272

45

28208

Of course, the statistical results are obvious. Except in vs08, sort () is indeed not very fast (especially in vc6), followed by quicksort and heapsort. For heapsort, the heap here is expressed in sequence, which saves a lot of time.

What's amazing is that the merge in vc6 is slower than the bubble. It's not reasonable. Of course, it's good that a standard C ++ test like GCC gives us confidence.

I just found that the insertion was not done after statistics, and I added the statistical results. Now, that's the case. What's wrong? Please follow the instructions to modify it.

Note: Later I switched to two-way bubbling and found that it was more than twice faster than the original bubble and a little faster than the choice (later I tested it, the initial writing failed, but it was actually the same as the one-way bubble speed)

CodeAs follows:

 
For (I = 0; I <Max; I ++) {k = MAX-i-1; For (j = I + 1; j <K; j ++) // use bidirectional bubble {If (V [J] <V [I]) {swap (& V [I], & V [J]);} if (V [MAX-j-1]> V [k]) {swap (V [MAX-j-1], V [k]) ;}}

The running time result is updated immediately.

I wanted to change the option to a two-way choice, with Min storage low, Max having high, and j <max-I in the second loop, but there were some problems, such as the possibility of two exchanges, after the Min-cycle exchange, another Max exchange is not the expected result. Please try again later.

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.