Guest User

Untitled

a guest
Apr 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #define MAX 10
  6. #define ARRAY_SIZE 10
  7.  
  8. void swap( int x, int y, int array[] ){
  9. int aux;
  10. // aux assume o valor de x
  11. aux = array[x];
  12. // valor de y é guardado na posicao x
  13. array[x] = array[y];
  14. // valor anterior de x é guardado na posicao y
  15. array[y] = aux;
  16. }
  17.  
  18. int bubbleSort(int* num, int array_size, int asc){
  19. int temp, loops=0;
  20. // corre pelo array
  21. for(int i = 1; i < array_size; i++) {
  22. int trocou=0;
  23. // para cada posicao do array
  24. for(int j = 0; j < array_size-i; j++ ) {
  25. if (asc){
  26. // compara com a proxima, se for maior, troca
  27. if(num[j] > num[j+1]) {
  28. swap(j, j+1, num);
  29. trocou=1;
  30. }
  31. }else{
  32. if(num[j] < num[j+1]) {
  33. swap(j, j+1, num);
  34. trocou=1;
  35. }
  36. }
  37. loops++;
  38. }
  39. // se nao houve troca, o array esta ordenado. Finaliza.
  40. if (trocou==0){
  41. return loops;
  42. }
  43. }
  44.  
  45. return loops;
  46. }
  47.  
  48. void printArray(int* num, int array_size) {
  49. // mostra um array, passando o tamanho
  50. for(int i = 0; i < array_size; ++i) {
  51. printf("array[%d] = %d\n", i, num[i]);
  52. }
  53. }
  54.  
  55. int main(){
  56. // declaramos o ponteiro
  57. int *ptrInt;
  58. // alocamos espaco
  59. ptrInt = malloc (ARRAY_SIZE * sizeof *ptrInt);
  60. // gerar numeros aleatorios
  61. srand(time(NULL)); // seed aleatoria
  62. for(int i = 0; i < ARRAY_SIZE; ++i) {
  63. // preencher o array com numeros de 0 até MAX
  64. ptrInt[i] = rand() % (MAX + 1 - 0) + 0;
  65. }
  66. // mostrar o array desordenado
  67. printf("Array desordenado: \n");
  68. printArray(ptrInt, ARRAY_SIZE);
  69. // array ordenado ascendente(1) ou descendentemente(0)
  70. int asc = 1;
  71. // ordenar o array
  72. int total_loops = bubbleSort(ptrInt, ARRAY_SIZE, asc);
  73. // mostrar o array ordenado
  74. printf("\nArray ordenado %s :\n", (asc == 1) ? "asc": "desc");
  75. printArray(ptrInt, ARRAY_SIZE);
  76. // mostrar quantas operaçoes foram realizadas
  77. printf("\nTotal de iterações: %i\n", total_loops);
  78. // liberar a memoria alocada
  79. if(ptrInt != NULL) {
  80. free(ptrInt);
  81. }
  82. // finaliza programa
  83. return 0;
  84. }
Add Comment
Please, Sign In to add comment