Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

PLease help me finish the rest of this code... C language and the this seem to be like add a number and make it in

PLease help me finish the rest of this code... C language and the this seem to be like add a number and make it in the right order ( small to big).

#include main() { int a[30]; int i, j, lasti; int num; lasti = 0;

printf("Enter an integer: "); scanf("%d", &a[0]); printf("array[0] is: %d ", a[0]);

while(1) {

printf("Enter an integer to be sorted: "); scanf("%d", &num); for(i = 0; i<=lasti; i++) { // if num is bigger than a[i] if( num < a[i] ) { // But we are sorting as a number_come_in bases, // a[0] < a[1] < a[2] < a[3] < ..... < a[lasti] // For example; // a[0] a[1] a[2] a[3] a[4] a[5] // 7 < 12 < 30 < 35 < 64 < 77 // // if a new comming_in number num is 20, // 20 <= 7 (a[0]) Nooooo // 20 <= 12 (a[1]) Nooooo // 20 <= 30 (a[2]) Ya ya ya! 20 should go in a[2] // When i is 2, 20<=30 is true ! That is the slot. // now, we have to move 77,64,35, and 30 to insert 20 // // a[0] a[1] a[2] a[3] a[4] a[5] a[6] // 7 < 12 < ____ 30 < 35 < 64 < 77 // This moving process can be done by the loop: //a[j+1] = a[j]; // Let's think about j's range // First one to move is a[lasti] to a[lasti+1] // So, we set j = lasti //a[j+1] = a[j]; // this moves a[lasti] to a[lasti+1] // Next, set j = j-1 //a[j+1] = a[j]; // this moves a[lasti-1] to a[lasti] // Next, set j = j-1 //a[j+1] = a[j]; // this moves a[lasti-2] to a[lasti-1] // Well, how long do we have to do this moving business? // When we finish moving a[i] to a[i+1]. a[i] is the slot. // In the above example, when 30 (a[2]) moved into a[3] // So, j goes from lasti down as long as j >= i for(j=lasti; j >= i; j--){ a[j+1] = a[j]; } // After the above moving business, // insert num into a[i] and get out the loop and

a[i] = num;

}

// if num is bigger than anyone in the array a[], // that means, "if( num < a[i] )" never be true, // then num should be placed in the end. // This case is detected when i is bigger than lasti if( i > lasti ) { a[i] = num; lasti++; } // print array { int i; for(i=0; i <= lasti; i++) printf("%d ", a[i]); printf("---------lasti=%d ", lasti);

} }

} }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Science Project Ideas In Health Care Volume 1

Authors: Zemelak Goraga

1st Edition

B0CPX2RWPF, 979-8223791072

More Books

Students also viewed these Databases questions