HW5 Part A


SUBMITTED BY: kmontambault

DATE: Dec. 16, 2016, 6:06 a.m.

FORMAT: C++

SIZE: 2.3 kB

HITS: 1405

  1. //HW5 part a
  2. //Nov 30, 2016
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <time.h>
  6. int **generatePointerArray(int);
  7. void ascendingSort(int **array, int len, int i);
  8. void descendingSort(int **array, int len, int i);
  9. int main(){
  10. int i;
  11. srand(time(NULL));
  12. int arrayLength = rand()%5+7;
  13. int array1[arrayLength]; //initialize an array of random length
  14. int **array2 = generatePointerArray(arrayLength); //allocates memory for a pointer array
  15. int **array3 = generatePointerArray(arrayLength); //allocates memory for a pointer array
  16. for(i=0; i<arrayLength; i++){ //generates an array of random integers and 2 pointer arrays that point to those values
  17. array1[i] = rand()%100;
  18. array2[i] = &array1[i];
  19. array3[i] = &array1[i];
  20. }
  21. ascendingSort(array2, arrayLength, 0); //sorts the pointer arrays without editing the origional arrays (ascending)
  22. descendingSort(array3, arrayLength, 0); //sorts the pointer arrays without editing the origional arrays (descending)
  23. printf("\tAscending\tOriginal\tDescending\n"); //prints the arrays in a nice format yay
  24. for(i=0; i<arrayLength; i++){
  25. printf("\t %d\t\t %d\t\t %d\n", *array2[i], array1[i], *array3[i]);
  26. }
  27. free(array2); //releases the allocated memory
  28. free(array3); //releases the allocated memory
  29. return 0;
  30. }
  31. int **generatePointerArray(int len){ //returns an array of pointers of length 'len'
  32. int **array = (int**)calloc(len+1, sizeof(int*));
  33. array[len] = NULL;
  34. return array;
  35. }
  36. void ascendingSort(int **array, int len, int i){ //selection sort
  37. int j;
  38. int *tmp;
  39. if(array[i] != NULL){
  40. for(j=i; j<len; j++){
  41. if(*array[i]>*array[j]){
  42. tmp = array[i];
  43. array[i] = array[j];
  44. array[j] = tmp;
  45. }
  46. }
  47. ascendingSort(array, len, i+1);
  48. }
  49. }
  50. void descendingSort(int **array, int len, int i){ //insertion sort algorithm
  51. int j;
  52. int *tmp1;
  53. tmp1 = array[i];
  54. for(j=i-1; j>=0; j--){
  55. if(*tmp1>*array[j]){
  56. array[j+1] = array[j];
  57. if(j==0){
  58. array[0] = tmp1;
  59. break;
  60. }
  61. }else{
  62. array[j+1] = tmp1;
  63. break;
  64. }
  65. }
  66. if(i+1<len){descendingSort(array, len, i+1);}
  67. }

comments powered by Disqus