08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 ■ Searching, Sorting, and Merging

void swap(int [], int, int);

for (int h = lo; h < hi; h++) {

int s = getSmallest(list, h, hi);

swap(list, h, s);

}

} //end selectionSort

int getSmallest(int num[], int lo, int hi) {

//find position of smallest from num[lo] to num[hi]

int small = lo;

for (int h = lo + 1; h <= hi; h++)

if (num[h] < num[small]) small = h;

return small;

} //end getSmallest

void swap(int num[], int i, int j) {

//swap elements num[i] and num[j]

int hold = num[i];

num[i] = num[j];

num[j] = hold;

} //end swap

The following is a sample run of the program:

Type up to 10 numbers followed by 0

57 48 79 65 15 33 52 0

The sorted numbers are

15 33 48 52 57 65 79

Comments on Program P9.1

The program illustrates how to read and store an unknown amount of values in an array. The

program caters for up to 10 numbers but must work if fewer numbers are supplied. We use n

to subscript the array and to count the numbers. Initially, n is 0. The following describes what

happens with the sample data:

• The 1st number, 57, is read; it is not 0 so we enter the while loop. We store 57

in num[0] then add 1 to n, making it 1; one number has been read and n is 1.

• The 2nd number, 48, is read; it is not 0 so we enter the while loop. We store 48

in num[1] then add 1 to n, making it 2; two numbers have been read and n is 2.

• The 3rd number, 79, is read; it is not 0 so we enter the while loop. We store

79 in num[2] then add 1 to n, making it 3; three numbers have been read and

n is 3.

250

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!