logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/sorts/insertionSort.c

/*

A demonstration of Insertion Sort

This works by taking elements from the list one by one and 
inserting them in their correct position into a new sorted 
list similar to how we put money in our wallet.

This Insertion Sort function takes in two arguments, the 
array and the size.

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 //or 2 to the 20th power

void insertionSort(int arr[], int size);

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
	}

	insertionSort(arr, sz);

	
	return 0;
}

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

	if(!arr)
		return;

  	int key, j;
    for(int i = 1; i < size; i++) {
        key = arr[i];
        j = i - 1;
 
        /* Move elements of arr[0..i-1], that are
          greater than key, to one position ahead
          of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }

}