Guest User

Untitled

a guest
Feb 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /*
  4. Modify the sort function from Program 8.12 to take a third argument indicating whether the array is to be sorted in ascending or descending order. Then modify the sort algorithm to correctly sort the array into the indicated order.
  5. */
  6.  
  7. //sort array ascending
  8. void sortAcc(int array[], int arrayLength){
  9. int i, j, temp;
  10. for(i = 0; i < arrayLength - 1; i++){
  11. for(j = i + 1; j < arrayLength; j++){
  12. if(array[i] > array[j]){
  13. temp = array[i];
  14. array[i] = array[j];
  15. array[j] = temp;
  16. }
  17. }
  18. }
  19. }
  20.  
  21. //sort array descending
  22. void sortDcc(int array[], int arrayLength){
  23. printf("descending");
  24. int i, j, temp;
  25. for(i = 0; i < arrayLength - 1; i++){
  26. for(j = i + 1; j < arrayLength; j++){
  27. if(array[i] < array[j]){
  28. temp = array[i];
  29. array[i] = array[j];
  30. array[j] = temp;
  31. }
  32. }
  33. }
  34. }
  35.  
  36. //sorting method
  37. void sortArray(int array[], int indexToRemove, int indexToReplace){
  38. int temp;
  39. temp = array[indexToRemove];
  40. array[indexToRemove] = array[indexToReplace];
  41. array[indexToReplace] = temp;
  42. }
  43.  
  44. //Sorting an array of integers into ascending or descending order
  45. void sort(int array[], int arrayLength, char sortOrder){
  46. int i, j;
  47. for(i = 0; i < arrayLength - 1; i++){
  48. for(j = i + 1; j < arrayLength; j++){
  49. if(sortOrder == 'd'){
  50. if(array[i] < array[j]){
  51. sortArray(array, i, j);
  52. }
  53. } else {
  54. if(array[i] > array[j]){
  55. sortArray(array, i, j);
  56. }
  57. }
  58. }
  59. }
  60. }
  61.  
  62. int main(void){
  63. int i;
  64. int array[16] = { 34, -5, 6, 0, 12, 100, 56, 22,
  65. 44, -3, -9, 12, 17, 22, 6, 11};
  66. void sort(int a[], int n, char o);
  67.  
  68. printf("The array before the sort: \n");
  69.  
  70. for(i = 0; i < 16; i++){
  71. printf("%i ", array[i]);
  72. }
  73.  
  74. sort(array, 16, 'd');
  75.  
  76. printf("\n\nThe array after the sort:\n");
  77.  
  78. for(i = 0; i < 16; i++){
  79. printf("%i ", array[i]);
  80. }
  81. printf("\n");
  82.  
  83. return 0;
  84. }
Add Comment
Please, Sign In to add comment