logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/sorts/selectionSort.c

/*

A demonstration of Selection Sort.

This works by finds the minimum value, swaps it with the 
value in the first position, and repeats these steps for the 
remainder of the list.

this is just a demonstration file, where you input a number,
and it'll create an array with that many elements, and also
generate that number of random numbers.

*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 1048576

void selectionSort(int arr[], int size);
void swap(int *x, int *y);

int main(int argc, char *argv[]){

	if(argc < 2){
		fprintf(stderr, "Usage: %s <number>\n", argv[0]);
		exit(1);
	}

	int sz = atoi(argv[1]);

	if(sz > MAX || sz < 1){
		fprintf(stderr, "Error: This value is not allowed\n");
		exit(1);
	}

	int arr[sz];
	time_t t;

   /* Intializes random number generator */
	srand((unsigned) time(&t)); //seeding it to the computers clock	

	for(int i = 0; i < sz; i++){
		arr[i] = rand() % sz; //generating an array of random numbers
	}

	selectionSort(arr, sz);

	
	return 0;
}

void selectionSort(int arr[], int size){

    int i, j, min_idx;
 
    // One by one move boundary of unsorted subarray
    for (i = 0; i < size-1; i++) {
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < size; j++)
          if (arr[j] < arr[min_idx])
            min_idx = j;
 
        // Swap the found minimum element with the first element
        swap(&arr[min_idx], &arr[i]);
    }
}
void swap(int *x, int *y){

	int tmp = *x;
	*x = *y;
	*y = tmp;

}