08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9 ■ Searching, Sorting, and Merging

With getSmallest and swap, we can code the algorithm, above, as a function selectionSort. To

emphasize that we can use any names for our parameters, we write the function to sort an integer

array called list. To make it general, we also tell the function which portion of the array to sort by

specifying subscripts lo and hi. Instead of the loop going from 0 to n-2 as in the algorithm, it now

goes from lo to hi-1 – just a minor change for greater flexibility.

//sort list[lo] to list[hi] in ascending order

void selectionSort(int list[], int lo, int hi) {

int getSmallest(int [], int, int);

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

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

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

swap(list, h, s);

}

} //end selectionSort

We now write Program P9.1 to test whether selectionSort works properly. The program

requests up to 10 numbers (since the array is declared to be of size 10), stores them in the array

num, calls selectionSort, then prints the sorted list.

Program P9.1

#include <stdio.h>

int main() {

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

int v, num[10];

printf("Type up to 10 numbers followed by 0\n");

int n = 0;

scanf("%d", &v);

while (v != 0) {

num[n++] = v;

scanf("%d", &v);

}

//n numbers are stored from num[0] to num[n-1]

selectionSort(num, 0, n-1);

printf("\nThe sorted numbers are\n");

for (int h = 0; h < n; h++) printf("%d ", num[h]);

printf("\n");

} //end main

void selectionSort(int list[], int lo, int hi) {

//sort list[lo] to list[hi] in ascending order

int getSmallest(int [], int, int);

249

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!