Chapter 1 Basic Concepts

1.1 Overview:System Life Cycle

1.2 Algorithm Specification

Program 1.1 : Selection sort algorithm

for(i = 0; i < n; i++){
   Examine list[i] to list[n-1] and suppose that the smallest integer is at list[min];
   
   Interchange list[i] and list[min];
}

Program 1.2 : Swap function

/* both parameters are pointers to ints */
void swap(int * x, int * y) {
   int temp = * x; /* declares temp as an int and assigns to it the contents of what x points to */
   * x = * y; /* stores what y points to into the location where x points */
   * y = temp; /* places the contents of temp in location pointed to by y */
}

Program 1.3 : Selection sort

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 101
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t)) //swap macro
void sort(int[], int); /* selection sort */

int main(void) {
   int i, n;
   int list[MAX_SIZE];
   printf("Enter the number of numbers to generate: ");
   scanf("%d", &n);
   if(n < 1 || n > MAX_SIZE) {
      fprintf(stderr, "Improper value of n\n");
      exit(1);
   }
   for(i = 0; i < n; i++) { /* randomly generate numbers */
      list[i] = rand() % 1000;
      printf("%d ", list[i]);
   }
   sort(list, n);
   printf("\n Sorted array:\n ");
   for(i = 0; i < n; i++) /* print out sorted numbers */
      printf("%d ", list[i]);
   printf("\n");
}

void sort(int list[], int n) {
   int i, j, min, temp;
   for(i = 0; i < n - 1; i++) {
      min = i;
      for(j = i + 1; j < n; j++) {
         if(list[j] < list[min])
            min = j;
      }
      SWAP(list[i], list[min], temp);
   }
}