//HW5 part a
//Nov 30, 2016
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int **generatePointerArray(int);
void ascendingSort(int **array, int len, int i);
void descendingSort(int **array, int len, int i);
int main(){
int i;
srand(time(NULL));
int arrayLength = rand()%5+7;
int array1[arrayLength]; //initialize an array of random length
int **array2 = generatePointerArray(arrayLength); //allocates memory for a pointer array
int **array3 = generatePointerArray(arrayLength); //allocates memory for a pointer array
for(i=0; i<arrayLength; i++){ //generates an array of random integers and 2 pointer arrays that point to those values
array1[i] = rand()%100;
array2[i] = &array1[i];
array3[i] = &array1[i];
}
ascendingSort(array2, arrayLength, 0); //sorts the pointer arrays without editing the origional arrays (ascending)
descendingSort(array3, arrayLength, 0); //sorts the pointer arrays without editing the origional arrays (descending)
printf("\tAscending\tOriginal\tDescending\n"); //prints the arrays in a nice format yay
for(i=0; i<arrayLength; i++){
printf("\t %d\t\t %d\t\t %d\n", *array2[i], array1[i], *array3[i]);
}
free(array2); //releases the allocated memory
free(array3); //releases the allocated memory
return 0;
}
int **generatePointerArray(int len){ //returns an array of pointers of length 'len'
int **array = (int**)calloc(len+1, sizeof(int*));
array[len] = NULL;
return array;
}
void ascendingSort(int **array, int len, int i){ //selection sort
int j;
int *tmp;
if(array[i] != NULL){
for(j=i; j<len; j++){
if(*array[i]>*array[j]){
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
ascendingSort(array, len, i+1);
}
}
void descendingSort(int **array, int len, int i){ //insertion sort algorithm
int j;
int *tmp1;
tmp1 = array[i];
for(j=i-1; j>=0; j--){
if(*tmp1>*array[j]){
array[j+1] = array[j];
if(j==0){
array[0] = tmp1;
break;
}
}else{
array[j+1] = tmp1;
break;
}
}
if(i+1<len){descendingSort(array, len, i+1);}
}