Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 39

C Exercise 39

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** There is an already sorted array. Now enter a number and insert it into the array according to the original order.

**Program Analysis:** First determine whether this number is greater than the last number, then consider the case of inserting it in the middle. After insertion, the numbers after this element are each shifted back one position.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

int

main

(

)

{

int

a

[

11

]

=

{

1

,

4

,

6

,

9

,

13

,

16

,

19

,

28

,

40

,

100

}

;

int

temp1

,

temp2

,

number

,

end

,

i

,

j

;

printf

(

"

The original array is:

\

n

"

)

;

for

(

i

=

0

;

i

<

10

;

i

++

)

printf

(

"

%4d

"

,

a

[

i

]

)

;

printf

(

"

\

n Insert a new number:

"

)

;

scanf

(

"

%d

"

,&

number

)

;

end

=

a

[

9

]

;

if

(

number

end

)

a

[

10

]

=

number

;

else

{

for

(

i

=

0

;

i

<

10

;

i

++

)

{

if

(

a

[

i

]

number

)

{

temp1

=

a

[

i

]

;

a

[

i

]

=

number

;

for

(

j

=

i

1

;

j

<

11

;

j

++

)

{

temp2

=

a

[

j

]

;

a

[

j

]

=

temp1

;

temp1

=

temp2

;

}

break

;

}

}

}

for

(

i

=

0

;

i

<

11

;

i

++

)

printf

(

"

%4d

"

,

a

[

i

]

)

;

printf

(

"

\

n

"

)

;

return

0

;

}

The output of the above example is:



The original array is:

   1   4   6   9  13  16  19  28  40 100

插入一个新的数字: 10

   1   4   6   9  10  13  16  19  28  40 100

100 Classic C Language Examples 100 Classic C Language Examples