Sorting in C++ vs. C


There is a tradeoff between writing special-case code yourself, calling a special-case library routine, and calling a general-case library routine. I would like to have:

  • Speed: Naturally, I want my program to run as fast as possible. General-case library code usually does not give me speed, because it’s not optimized for my particular situation. I’d be better off using special-case code. Hand-written code is usually (but not always) best here, because it can take advantage of specialized knowledge of the data.
  • Flexibility: I want to have code that works in many different situations. Special-case library code does not give me flexibility, because it’s only written for certain situations. I’d be better off using a general-case library routine or my own code (which I can copy and modify in new situations) for flexibility. A general-case library is best because I don’t have to copy and paste (a maintenance nightmare).
  • Ease of Coding: I want to write as little as possible to get the job done. Writing code myself does not satisfy this goal. I’d be better off using a library routine. Special-case library routines are best because I don’t have to specify as many parameters.

As you can see, none of the solutions gives me all three. Given any one goal, there is a corresponding best solution. Given any one solution, I can only get two out of three goals. In this document I present a comparison of sorting in C and C++, and show that with C++ STL, you can get all three.

Appendix: Running Times

Data
Type

C
(library)

C
(hand-coded)

Numerical
Recipes

Ratio
1

C++
(C array)

C++
(vector class)

Ratio
2

int

5.90-5.92

1.54-1.65

1.46-1.50

3.7

1.12-1.16

1.11-1.14

5.3

short

9.03-9.03

1.73-1.80

1.58-1.59*

5.1

1.17-1.20

1.17-1.19

7.7

byte

7.87-7.89

0.98-1.02

0.98-1.00

7.9

0.70-0.73

0.70-0.73

11.0

float

7.08-7.10

2.38-2.50

2.48-2.55

2.9

1.96-2.02

1.97-2.02

3.6

double

16.42-16.45

2.70-2.93

2.72-2.83

5.8

2.28-2.35

2.28-2.37

7.1

by Amit Patel

http://theory.stanford.edu/~amitp/rants/c++-vs-c/

Programming Tutorials

http://www.cprogramming.com/tutorial.html

Advertisement

2 thoughts on “Sorting in C++ vs. C

  1. Sophie

    恩,以后你这儿写的偶就直接贴到我的notebook里去~~ 嘿嘿~
     
    P.S. 一开始以为开头那一大段是Andy写的… 汗… 英语写的很地道的说…

    Reply
  2. Feng

    是我写的话,肯定就是中文了,写这么长还有挑战性的,
     
    不过,这篇文章确实修正了我对stl及其容量器的看法

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s